为什么赋值运算符允许返回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以便你可以进行赋值链接”,这完全是有道理的,但是为什么上述工作有效呢?
试试看:
   使用上面代码的在线 c++ 工作区