在 C++ 中将字符* 转换为常量字符*

convert char* to const char* in C++

本文关键字:字符 常量 转换 C++      更新时间:2023-10-16

如何在C++中将char*转换为const char*?为什么程序 1 有效,而程序 2 不能?

方案 1(工作(:

char *s = "test string";
const char *tmp = s;
printMe(tmp);
void printMe(const char *&buf) {
    printf("Given Str = %s", buf);
}

程序 2(不工作(

char *s = "test string";
printMe((const char *)s);     // typecasting not working
void printMe(const char *&buf) {
    printf("Given Str = %s", buf);
}

我收到的错误:

x.cpp:10:15: warning: conversion from string literal to 'char *' is 
deprecated [-Wc++11-compat-deprecated-writable-strings]
char *s = "test string";
          ^
x.cpp:12:5: error: no matching function for call to 'printMe'
printMe(s);
^~~~~~~
x.cpp:6:6: note: candidate function not viable: no known conversion 
from 'char *' to 'const char *&' for 1st argument
void printMe(const char *&buf)
 ^
1 warning and 1 error generated.

谢谢。

printMe采用对指向常量字符的可变指针的左值引用。

在您的第一个示例中,tmp 是指向 const char 的可变指针类型的左值,因此可以将引用绑定到它而不会出现问题。
在第二个示例中,(const char*)s创建一个临时const char*对象。 对可变对象的左值引用无法绑定到临时对象,因此会出现错误。 如果将printMe更改为采用const char* const&则无论是否显式强制转换,调用都将成功。

void printMe(const char * const& buf) {
    printf("Given Str = %s", buf);
}
int main() {
    char s[] = "test string";
    printMe(s);
}

住在科里鲁

当然,如果您不想更改传递给printMe的对象(指针(,那么根本没有理由使用引用。 只需让它需要const char*

void printMe(const char * buf) {
    printf("Given Str = %s", buf);
}
int main() {
    char s[] = "test string";
    printMe(s);
}

住在科里鲁

最后,这与类似的原因相同:

void doSomething(const std::string& s) {}
int main() {
    doSomething("asdf");
}

在此工作时:

void doSomething(std::string& s) {}
int main() {
    doSomething("asdf");
}

不。 将创建一个临时对象,并且对非 const 对象的引用无法绑定到临时对象。