Answer the question
In order to leave comments, you need to log in
How to return a reference to an object?
Hello!
There is a task of application at once two methods to one object of a class. For example, there is an object from the Complex class. It is necessary that such a construction work correctly: c.sum(a).sub(b). As I understand it, it is necessary that the sum method returns a reference to the object in order for the second method to be applied correctly.
Please explain how to do this. Is it possible to implement this without the help of creating a temporary object, that is, to immediately return a reference to the updated object c?
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
Do at the end of the necessary methods. For example:return *this
class XXX {
double val;
public:
XXX(double v) {
val = v;
}
XXX& add(double v) {
val += v;
return *this;
}
XXX& sub(double v) {
val -= v;
return *this;
}
friend std::ostream& operator <<(std::ostream &os, const XXX &x) {
return os << x.val;
}
};
...
std::cout << XXX(5).sub(1).add(2).sub(3).add(4) << endl; // 7
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question