如何在C++中将char *转换为const char *?为什么程序1正在工作,但程序2不能?在C++中将char *转换为const char *
PROG 1(工作):
char *s = "test string";
const char *tmp = s;
printMe(tmp);
void printMe(const char *&buf) {
printf("Given Str = %s", buf);
}
PROG 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.
这不是有效的C,它是C++。在* both *语言中,你做错了......指针's'是一个指向*只读*(在C++中为'const')字符数组的指针,所以's'应该是'const char * s =“test string”;' –
哦,好吧!我很抱歉,我正在尝试使用g ++进行编译。让我改变标题。 –
在Prog 2中没有定义tmp? –