对于级联成员函数调用,为什么我需要返回引用?为什么不只是这个指针足够了?

Arm*_*fai 0 c++ reference function cascading this-pointer

#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();
}
Run Code Online (Sandbox Code Playgroud)
  1. 为什么我不能只用这个指针返回对象来进行级联函数调用?
  2. 为什么我需要返回对象的引用?
  3. 甚至会做什么?

das*_*ght 6

返回this指针也足够了.但是,级联调用的语法需要在链的中间进行更改:

s.setA(8)->setB(9)->setC(10);
Run Code Online (Sandbox Code Playgroud)

这看起来不一致,因此返回引用是更好的选择.