我有以下代码:转换的char *字符串和
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string &s1 = argv[0]; // error
const string &s2 = argv[0]; // ok
argv[0] = "abc";
cout << argv[0] << endl; // prints "abc"
cout << s2 << endl; // prints program name
}
我收到s1
以下错误:
invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'char*'
那么为什么编译器接受s2
?
有趣的是,当我为argv[0]
指定一个新值时,s2
不会改变。编译器是否忽略它是一个引用并且复制该值?为什么会发生?
我在Code :: Blocks 16.01(mingw)中写这个。有/无-std=c++11
。
你会说'argv [0]'是一个'std :: string'吗? – Biffen
“那为什么编译器接受s2?”由于隐式转换。 http://stackoverflow.com/questions/4553896/conversion-of-char-to-string –