繁体   English   中英

在C ++中将char *转换为const char *

[英]convert char* to const char* in C++

如何在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.

谢谢。

printMe对一个指向const char的可变指针进行左值引用。

在你的第一个例子中, tmp是一个类型为const char的可变指针的左值,因此引用可以没有问题地绑定到它。
在第二个示例中, (const char*)s创建一个临时的const char*对象。 Lvalue对可变对象的引用无法绑定到临时对象,因此您会收到错误。 如果您更改printMe以获取const char* const&那么无论是否使用显式printMe转换,调用都将成功。

void printMe(const char * const& buf) {
    printf("Given Str = %s", buf);
}

int main() {
    char s[] = "test string";
    printMe(s);
}

住在Coliru

当然,如果你不想改变传递给printMe的对象(指针),那么根本没有理由使用引用。 只需要一个const char*

void printMe(const char * buf) {
    printf("Given Str = %s", buf);
}

int main() {
    char s[] = "test string";
    printMe(s);
}

住在Coliru

最后,这是同样的原因:

void doSomething(const std::string& s) {}
int main() {
    doSomething("asdf");
}

适用于此:

void doSomething(std::string& s) {}
int main() {
    doSomething("asdf");
}

才不是。 创建临时对象,并且对非const对象的引用无法绑定到临时对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM