如何在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.
谢谢。
s
是指向一个只读(在C++中为const
)字符数组的指针,所以s
应该是const char *s = "test string";
- Some programmer dudeconst char *tmp = s;
将char *
转换为const char *
吗?因此,显然其中一条路径是成功的。 - chux - Reinstate Monica