让所有的setter函数都返回对c++中对象的引用好吗?
最佳答案
如果需要在对象上设置很多东西,这是一个足够可用的模式。
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);
}
这个模式替换了一个需要三个整数的构造函数:
int main()
{
Foo foo(1, 2, 3); // Less self-explanatory than the above version.
}
如果您有许多并不总是需要设置的值,这很有用。
作为引用,此类技术的更完整示例在 C++ FAQ Lite 中称为“Named Parameter Idiom”。
当然,如果您将其用于命名参数,您可能需要查看 boost::parameter .或者你可能不会......
关于c++ - 让所有 setter 函数返回对 c++ 中对象的引用是否很好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/752762/