下面的代碼編譯和工作。爲什麼不產生錯誤:「不能從'const std :: string'轉換爲'std :: string &'」?爲什麼在設置類成員時自動從const轉換爲非const&發生?
class Test {
private:
std::string& _str;
public:
Test(std::string& str) : _str(str)
{ }
void SetStr(const std::string& str)
{
// std::string& s = str; // error: cannot convert from 'const std::string' to 'std::string &'
_str = str; // strange, but it works!
_str.append(", world!"); // it works too
}
const std::string& GetStr()
{
return _str;
}
};
...
std::string str = "";
Test test(str);
test.SetStr("Hello");
std::cout << test.GetStr(); // prints "Hello, world!"
std::cout << str; // also prints "Hello, world!"