0
// have compilation errors
class TestClass
{
public:
TestClass(std::string& str) {}
};
int main() {
TestClass tc(std::string("h"));
return 0;
}
p166.cpp: In function ‘int main()’:
p166.cpp:29:32: error: no matching function for call to ‘TestClass::TestClass(std::string)’
p166.cpp:25:3: note: candidates are: TestClass::TestClass(std::string&)
p166.cpp:23:1: note: TestClass::TestClass(const TestClass&)
// have NO compilation errors
class TestClass2
{
public:
TestClass2(const std::string& str) {}
};
int main() {
TestClass2 tc(std::string("h"));
return 0;
}
問題>爲什麼第一部分(識別TestClass)具有編譯錯誤的對象? 是否因爲非const引用不能引用臨時對象而const引用可以引用臨時對象?初始化臨時實例
謝謝