欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c++this指针演示链式编程思想

程序员文章站 2022-07-12 16:29:47
...

举例说明

Worker员工类,有workerA,workerB两个人,通过workerA.addMoney(workerB).addMoney(workerB)…不断把B的工资累加到A的工资上。

关键函数Worker& addMoney(Worker& workerB)注意点:

  1. 返回类型需要是引用,只有返回自身才可以不断添加(不可以为拷贝)
  2. 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;
}


相关标签: 个人日记