c++this指针演示链式编程思想
程序员文章站
2022-07-12 16:29:47
...
举例说明
Worker员工类,有workerA,workerB两个人,通过workerA.addMoney(workerB).addMoney(workerB)…不断把B的工资累加到A的工资上。
关键函数Worker& addMoney(Worker& workerB)注意点:
- 返回类型需要是引用,只有返回自身才可以不断添加(不可以为拷贝)
- return *this表示返回this指针指向的实体本身类型
代码如下
#include<iostream>
using namespace std;
class Worker{
public:
Worker(int salary){
this->salary = salary;
}
Worker& addMoney(Worker& workerB){
this->salary +=workerB.getSalary();
return *this;
}
int getSalary(){
return this->salary;
}
private:
int salary;
};
int main(){
Worker workerA(10);
Worker workerB(5);
cout<<workerA.getSalary()<<endl;//10
workerA.addMoney(workerB).addMoney(workerB).addMoney(workerB);
cout<<workerA.getSalary()<<endl;//10+5+5+5=25
return 0;
}
上一篇: java json 对象操作
下一篇: 编程思想-链式编程