class SomeClass {
int a;
int b;
public:
SomeClass& Multiply();
SomeClass& Divide();
};
SomeClass& SomeClass::Multiply() {
a *= b;
return *this;
}
SomeClass& SomeClass::Divide() {
a /= b;
return *this;
}
int main( int argc, char* argv[] ) {
SomeClass theClass;
theClass.Multiply().Divide(); // this is possible because Multiply() returns
// a reference to theClass
return 0;
}
i know what's this pointer is,but i don't figure out what's it's benefit other than returning the instance of the current object !
You have to thing about the object is used.
In C, it is not uncommon to see code like:
1 2
int i, j, k, sum;
i = j = k = sum = 0;
How can we write code like:
1 2
std::string a, b, c, name;
a = b = c = name = "empty";
We can do that if we make operator= return a reference to the object (rather than a pointer to it). So one that sense, it can be thought of as syntactic sugar. But more importantly, it's providing an effect that we want.
another benefit (which i see it's usless) is using it to deal with local instance variables,which u can use them without using the pointer !
I never use this->x to access member variables. Personally, I think it shows lack of familiarity with the language.