让所有的 setter 函数都返回对 C++ 中对象的引用是否很好? [英] Is it good to have all the setter functions return a reference to the object in c++?
问题描述
让所有的 setter 函数都返回对 C++ 中对象的引用是否好?
Is it good to have all the setter functions return a reference to the object in c++?
推荐答案
如果需要在一个对象上设置很多东西,这是一个足够可用的模式.
It's a usable enough pattern if there's a lot of things that need to be set on an object.
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);
}
这个模式替换了一个接受三个整数的构造函数:
This pattern replaces a constructor that takes three ints:
int main()
{
Foo foo(1, 2, 3); // Less self-explanatory than the above version.
}
如果您有许多并不总是需要设置的值,它会很有用.
It's useful if you have a number of values that don't always need to be set.
作为参考,此类技术的更完整示例称为C++ FAQ Lite 中的命名参数习语.
For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite.
当然,如果您将其用于命名参数,您可能需要查看 boost::parameter.或者你可能不会...
Of course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not...
这篇关于让所有的 setter 函数都返回对 C++ 中对象的引用是否很好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!