C++ 类返回this 链式编程

553 阅读1分钟
class Person{
pubilc:
    Person(int age){
        this->age = age;
    }
    Person& AddAge(Person &p){ //要引用就要引用的方式返回 否则就是以值的方式返回
        this->age += p.age;
        return *this; //返回对象本身
    }
    int age;
}
void test01(){
    Person p1(18);
    Person p2(10);    
    Person p3(10);   
    p1.AddAge(p2).AddAge(p3).AddAge(p1);
}
  • 另一种情况 image.png