为什么允许赋值运算符返回void?为什么分配链在这种情况下起作用?看一下代码,我会非常清楚我在说什么.
码:
struct Foo
{
std::string str;
Foo(const std::string& _str)
: str(_str)
{
}
Foo& operator=(const Foo& _foo)
{
str = _foo.str;
//return *this; /* NO RETURN! */
}
};
int main()
{
Foo f1("1");
Foo f2("2");
Foo f3("3");
f1 = f2 = f3 = Foo("4");
std::cout << "f1: " << f1.str << std::endl;
std::cout << "f2: " << f2.str << std::endl;
std::cout << "f3: " << f3.str << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题:
我读过很多地方"赋值运算符应返回*这让你可以有任务链",这完全是有道理的,但后来为什么上面的工作?
试一试: …