如何在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
采用左值引用指向const char的可变指针。
在第一个示例中,tmp
是指向const char的可变指针类型的左值,因此可以将引用绑定到它而不会出现问题。
在第二个示例中,(const char*)s
创建一个临时const char*
对象。对可变对象的左值引用不能绑定到临时对象,因此会出现错误。如果更改printMe
为采用a,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对象的引用不能绑定到该临时对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句