In the class below. I am struggling to understand why you would return a reference to the class from a member function.
For example setInterval() initializes the member variable 'interval. Could anybody explain the advantage of returning a reference of the class type?
Is it a reference to *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.
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.
You'll see this approach used a lot more in things like operator<<
for streams which is chained by design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.