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)
返回this
指针也足够了.但是,级联调用的语法需要在链的中间进行更改:
s.setA(8)->setB(9)->setC(10);
Run Code Online (Sandbox Code Playgroud)
这看起来不一致,因此返回引用是更好的选择.
归档时间: |
|
查看次数: |
796 次 |
最近记录: |