小编Dar*_*rio的帖子

重载赋值运算符而不返回语句

为什么允许赋值运算符返回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)

问题:

  1. 为什么合法?(为什么要编译)
  2. 它为什么有效?

我读过很多地方"赋值运算符应返回*让你可以有任务链",这完全是有道理的,但后来为什么上面的工作?

试一试: …

c++ assignment-operator

5
推荐指数
1
解决办法
1063
查看次数

标签 统计

assignment-operator ×1

c++ ×1