【发布时间】:2016-11-11 02:10:19
【问题描述】:
我正在使用 g++4.1.2 编译这个:
cat 1.cpp
#include<iostream>
#include<string>
using namespace std;
void f(const string& s){}
void g(string& s){}
void h(string s){}
int main()
{
string s="abc";
f("abc");
g("abc”);//Error
h("abc");
return 0;
}
在“g();”行失败
$ g++ 1.cpp
1.cpp: In function ‘int main()’:
1.cpp:11: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’
1.cpp:5: error: in passing argument 1 of ‘void g(std::string&)’
我不太明白,只要“abc”可以是std::string的构造函数参数:
对于f(),“abc”可以用来构造一个字符串(const char*),作为对字符串的const引用
对于 h(),“abc”可用于构造一个右值的临时 std::string 对象。
对于g(),为什么不能用来构造左值引用字符串&,而const引用字符串&可以?
【问题讨论】:
-
你在
g调用中使用了一个奇怪的引号......它应该是" -
总之,左值引用不能绑定到临时的。
标签: c++ string char constants literals