[英]C++ - why return a reference to the class from a member function
In the class below.在class下面。 I am struggling to understand why you would return a reference to the class from a member function.
我很难理解为什么你会从成员 function 返回对 class 的引用。
For example setInterval() initializes the member variable 'interval.例如 setInterval() 初始化成员变量 'interval. Could anybody explain the advantage of returning a reference of the class type?
任何人都可以解释返回 class 类型的引用的优势吗?
Is it a reference to *this?它是对 *this 的引用吗?
template <class Tx, class Ty = Tx>
class FitFunction {
std::pair<Tx, Tx> interval;
uint8_t var = 0;
public:
FitFunction& setInterval(Tx minX, Tx maxX);
};
That's not a reference to the class, it's a reference to an instance of the class.这不是对 class 的引用,而是对 class实例的引用。
This is typical in functions you want to be chainable, as in:这在您希望可链接的函数中很典型,例如:
FitFunction ff;
ff.setInterval(...).setSomethingElse(...);
Where the idea is that function does a return *this
at the end, so yes, effectively a reference to that.想法是 function 最后
return *this
,所以是的,实际上是对它的引用。
You'll see this approach used a lot more in things like operator<<
for streams which is chained by design.您会看到这种方法更多地用于诸如
operator<<
之类的设计中链接的流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.