在 C++ 中返回“this”? (return "this" in C++?)


問題描述

在 C++ 中返回“this”? (return "this" in C++?)

In 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;
    }
}

參考解法

方法 1:

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.

方法 2:

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

方法 3:

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.

(by nobodyRobᵩlucky85doglittleadv)

參考文件

  1. return "this" in C++? (CC BY-SA 3.0/4.0)

#return #this #C++






相關問題

如果評估的最後一個語句是 If 語句,Ruby 會返回什麼 (What is Returned in Ruby if the Last Statement Evaluated is an If Statement)

將多個參數傳遞給 javascript 並根據兩個參數 + php 循環更新 html 內容 (pass multiple parameters to a javascript and update html content bases on both parameters + php loop)

Loại Không khớp không thể chuyển đổi từ Boolean sang Int (Mảng trong phương thức tùy chỉnh) (Type Mismatch can't convert from Boolean to Int (Arrays in custom method))

C++返回一個帶有私有構造函數的類實例 (C++ return a class instance with private constructor)

ArrayList.isEmpty() 時如何返回值? (How do I return a value when ArrayList.isEmpty()?)

如何將坐標(元組)格式化為字符串? (How can I format a coordinate (tuple) as a string?)

void 類型方法表達式體成員允許非 void 類型的表達式 *如果其他方法* (Void-type method expression-bodied member allows expression of non-void type *if other method*)

paypal動態退貨地址 (paypal dynamic return address)

讓兩個類進行交互 (getting two classes to interact)

在 C++ 中返回“this”? (return "this" in C++?)

Java:枚舉的不同返回類型 (Java: Different return type by enum)

如何檢查函數參數和類型 (How to inspect function arguments and types)







留言討論