#include<iostream>
#include<string>
using namespace std;

class Person {

public:
    int age;
    int scores;
    Person(int age) {
        this->age = age;    //this关键词指向 被调用的成员函数所属的对象,也就是p1
    }
    void test1( Person & p) {
        this->age += p.age;
        cout << "年龄为:" << age << endl;

    }

    Person& test2(Person & p) {  //引用方式返回
        this->age += p.age;
        cout << "年龄为:" << age << endl;
        return *this;   //this是一个指针,就是被调用所属的对象,解引用返回该对象,就可以无限用.调用他,如main函数的test2
        //在类的非静态成员函数中返回对象本身,可以使用 return *this
    }
};
int main() {
    Person p1(10);
    p1.test1(p1); //输出为36

    Person p2(15);
    p2.test2(p2).test2(p2).test2(p2); // 输出为 30,60,120 链式编程




}

延伸阅读:
https://www.5yang.cc/5973

最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏