【发布时间】:2013-03-06 15:40:19
【问题描述】:
为什么允许赋值运算符返回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;
}
问题:
- 为什么这是合法的? (为什么要编译)
- 为什么有效?
我在很多地方都读过“赋值运算符应该返回 *this 以便您可以进行赋值链接”,这完全有道理,但是为什么上述工作有效?
【问题讨论】:
-
它返回
Foo&,而不是void。