【发布时间】:2017-06-19 18:06:44
【问题描述】:
如何在 C++ 中将char* 转换为const char*?为什么程序 1 可以工作,而程序 2 不能?
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?
-
我认识@some 程序员老兄。但我想知道有没有办法将 char * 转换为 const char * 或反之亦然?
-
const char &buf, & 表示它绑定到一个变量,在第一种情况下它是 tmp。在第二种情况下,由于您没有 tmp,它无法将 char 转换为有界变量。如果 printMe 所做的只是 printf,则不需要 const char*& buf,只需要 const char* buf。
标签: c++ pointers casting reference constants