让所有setter函数在c ++中返回对象的引用是否很好?

yes*_*aaj 11 c++ reference return-type

让所有setter函数在c ++中返回对象的引用是否很好?

Ecl*_*pse 19

如果需要在对象上设置很多东西,那么这是一个可用的模式.

 class Foo
 {
      int x, y, z;
 public:
      Foo &SetX(int x_) { x = x_;  return *this; }
      Foo &SetY(int y_) { y = y_;  return *this; }
      Foo &SetZ(int z_) { z = z_;  return *this; }
 };

 int main()
 {
      Foo foo;
      foo.SetX(1).SetY(2).SetZ(3);
 }
Run Code Online (Sandbox Code Playgroud)

此模式替换了需要三个整数的构造函数:

 int main()
 {
      Foo foo(1, 2, 3); // Less self-explanatory than the above version.
 }
Run Code Online (Sandbox Code Playgroud)

如果您有许多值并不总是需要设置,那么它很有用.

作为参考,这种技术的更完整的例子被称为C++ FAQ Lite中的" 命名参数成语 ".

当然,如果你将它用于命名参数,你可能想看看boost ::参数.或者你可能不会......


Bri*_*ink 10

this如果要将setter函数调用链接在一起,可以返回引用,如下所示:

obj.SetCount(10).SetName("Bob").SetColor(0x223344).SetWidth(35);
Run Code Online (Sandbox Code Playgroud)

就个人而言,我认为代码比其他代码更难阅读:

obj.SetCount(10);
obj.SetName("Bob");
obj.SetColor(0x223344);
obj.SetWidth(35);
Run Code Online (Sandbox Code Playgroud)