在C ++中将char *转换为const char * [英] convert char* to const char* in C++

查看:392
本文介绍了在C ++中将char *转换为const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中将char*转换为const char*?为什么程序1可以运行,但是程序2不能运行?

How to convert char* to const char* in C++? Why program 1 is working but program 2 can't?

程序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的可变指针.

printMe takes an lvalue reference to a mutable pointer to const char.

在第一个示例中,tmp是指向const char的可变指针类型的左值,因此可以将引用绑定到它而不会出现问题.
在第二个示例中,(const char*)s创建一个临时const char*对象.对可变对象的左值引用不能绑定到临时对象,因此会出现错误.如果将printMe更改为const char* const&,则无论是否使用显式强制转换,调用都会成功.

In your first example, tmp is an lvalue of type mutable pointer to const char, so a reference can be bound to it without issue.
In your second example, (const char*)s creates a temporary const char* object. Lvalue references to mutable objects can't bind to temporaries, so you get an error. If you change printMe to take a const char* const& then the call will succeed with or without the explicit cast.

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

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

在Coliru上直播

当然,如果您不想更改传递给printMe的对象(指针),则完全没有理由使用引用.只需加上const char*:

Of course, if you don't want to alter the object (the pointer) passed into printMe, then there's no reason to use a reference at all. Just make it take a const char*:

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

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

在Coliru上直播

最后,这是类似的原因:

In the end, this is the same reason something like this:

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

在此期间工作:

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

没有.创建了一个临时对象,并且对非const对象的引用无法绑定到该临时对象.

does not. A temporary object is created, and the reference to non-const object can't bind to the temporary.

这篇关于在C ++中将char *转换为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆