如何在没有任何警告或错误的情况下进行编译和运行?我不明白如何将current的int 取消引用值分配给字符串,a而不会出现任何问题。
class Test {
public:
string a;
Test(initializer_list<int> t) {
auto current = t.begin();
// I am assigning an int to a string!
a = *current;
}
};
int main() {
Test test{65};
printf("%s\n", test.a.c_str());
}
Run Code Online (Sandbox Code Playgroud)
打印的字符串是
A
Run Code Online (Sandbox Code Playgroud)
相反,此非常相似的代码会产生编译时错误:
int main() {
initializer_list<int> test1{65};
auto current = test1.begin();
string b = *current;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
error: no viable conversion from 'const int' to 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
string b = *current;
Run Code Online (Sandbox Code Playgroud)