return “this” in C++?

前端 未结 3 1610
深忆病人
深忆病人 2020-12-13 10:24

In Java you can simply return this to get the current object. How do you do this in C++?

Java:

class MyClass {

    MyClass example() {
         


        
3条回答
  •  臣服心动
    2020-12-13 11:06

    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);
    

提交回复
热议问题