return "this" in C++?
In Java开发者_JAVA百科 you can simply return this
to get the current object. How do you do this in C++?
Java:
class MyClass {
MyClass example() {
return this;
}
}
Well, first off, you can't return anything from a void
-returning function.
There are three ways to return something which provides access to the current object: by pointer, by reference, and by value.
class myclass {
public:
// Return by pointer needs const and non-const versions
myclass* ReturnPointerToCurrentObject() { return this; }
const myclass* ReturnPointerToCurrentObject() const { return this; }
// Return by reference needs const and non-const versions
myclass& ReturnReferenceToCurrentObject() { return *this; }
const myclass& ReturnReferenceToCurrentObject() const { return *this; }
// Return by value only needs one version.
myclass ReturnCopyOfCurrentObject() const { return *this; }
};
As indicated, each of the three ways returns the current object in slightly different form. Which one you use depends upon which form you need.
One of the main advantages of return by reference in classes is the ability to easily chain functions.
Suppose that your member function is to multiply a particular member of your class.
If you make the header and source files to keep the information of the class and the definition of the member function separately, then,
the header file myclass.h
would be:
#ifndef myclass_h
#define myclass_h
class myclass{
public:
int member1_;
double member2_;
myclass (){
member1_ = 1;
member2_ = 2.0;
}
myclass& MULT(int scalar);
myclass* MULTP(double scalar);
};
#endif
and the source file: myclass.cpp
would be:
myclass& myclass::MULT(int scalar){
member1_ *= scalar;
return *this;
}
myclass* myclass::MULTP(double scalar){
member2_ *= scalar;
return this;
}
If you initialize an object called obj
, the default constructor above sets member1_
equal to 1:
Then in your main function, you can do chains such as:
myclass obj;
obj.MULT(2).MULT(4);
Then member1_
would now be 8. Of course, the idea might be to chain different functions,
and alter different members.
In the case you are using the return by pointer, the first call uses the object, and any subsequent call will treat the previous result as a pointer, thus
obj.MULTP(2.0)->MULTP(3.0);
Because the return type is void
, i.e.: you declare that you don't return anything. Change it to myclass*
to return this
change to myclass &
to return reference to the class through *this
.
精彩评论