簡體   English   中英

對於級聯成員函數調用,為什么需要返回引用? 為什么僅此指針還不夠?

[英]For cascading member function calls, why do i need to return the reference? Why isn't just the this pointer sufficient?

#include <iostream>

using namespace std;

class armon {
    int a;
    int b;

public:
    armon(int newA, int newB) : a(newA), b(newB) {}

    armon setA(int newA) {
        a = newA;
        return *this;
    }

    armon setB(int newB) {
        b = newB;
        return *this;
    }

    void print(void) { cout << a << endl << b; }
};

int main() {
    armon s(3, 5);

    s.setA(8).setB(9);

    s.print();
}
  1. 為什么我不能僅使用this指針返回對象以進行級聯函數調用?
  2. 為什么我需要返回對象的引用?
  3. 那會怎么辦?

返回this指針也將足夠。 但是,級聯調用的語法需要在鏈的中間進行更改:

s.setA(8)->setB(9)->setC(10);

這看起來不一致,因此返回引用是更好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM