在 C++ 中将字符* 转换为常量字符*
convert char* to const char* in C++
如何在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 对象的引用无法绑定到临时对象。
相关文章:
- 多字符常量警告
- const_cast<字符 *>(字符* 常量) 不是左值?
- 常量字符数组模板与字符常量* 函数重载
- 如何检查字符常量是否符合ASCII
- 从字符串数组转换为字符* 常量
- 字符常量或字符串常量
- 字符常量数组为空,即使已为其赋值 [C++]
- 如何创建 ' 字符常量
- 如何编写完全可移植的 4 字节字符常量的编译时初始化
- 我得到以下错误:[警告]多字符字符常量
- C++错误:警告:多字符字符常量/a用于用法
- 字符常量和函数名称的 sizeof() 背后的逻辑
- 如何在 C 中将多字符常量转换为整数
- C++ wifstream:不兼容的字符常量*,wchar_t康斯特*类型
- 不允许从"常量无符号字符*常量*"到"常量字符*常量*"static_cast
- 修改字符 *常量字符串
- 为什么字符常量/文字不能为空?
- C++字符 * 常量与字符 *,为什么有时一个有时另一个
- 警告多字符字符常量 [-Wmultichar]
- 开关语句多字符常量