在成员函数中返回* this [英] Returning *this in member functions
问题描述
我最近使用了一个允许使用以下类型语法的库:
I recently used a library that allows the following type of syntax:
MyClass myObject;
myObject
.setMember1("string value")
.setMember2(4.0f)
.setMember3(-1);
显然,这是通过让setter返回MyClass&类型;例如return * this。我喜欢这种代码的外观,但我看不到很多。当这种情况发生时,我通常怀疑为什么。
Obviously this is accomplished by having the setters return a MyClass & type; something like return *this. I like the way this code looks, but I don't see it a lot. When that happens I'm usually suspicious as to why.
那么,这是一个坏的做法吗?
So, is this a bad practice? What are some of the implications of doing it like this?
推荐答案
这有时被称为命名参数惯用法或方法链接。这不是坏的做法,它可以帮助可读性。考虑这个例子从C ++常见问题解答
This is sometimes referred to as the Named Parameter Idiom or method chaining. This isn't bad practice, it can aid readability. Consider this example lifted from the C++ FAQ
File f = OpenFile("foo.txt")
.readonly()
.createIfNotExist()
.appendWhenWriting()
.blockSize(1024)
.unbuffered()
.exclusiveAccess();
另一种方法是使用OpenFile方法的位置参数,要求程序员记住每个参数。
The alternative would be to use positional arguments to the OpenFile method, requiring the programmer to remember the position of each argument.
这篇关于在成员函数中返回* this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!