C++之链式调用
C++之链式调用
先不考虑函数返回值为引用的情况
代码如下:
#include <iostream> using namespace std; // this可以解决命名冲突 class Person{ public : Person(int age){ this->age = age; } Person(const Person &p){ this->age = p.age; } int age; void compareAge(Person &p) { if (this->age == p.age ){ cout << "Age is equal" << endl; } else cout << "Age is unequal" << endl; } Person addAge(Person &p ){ this -> age += p.age; return *this; // *this 指向本体 } }; void test01() { Person p1(10); Person p2(110); cout << p1.age << endl; p1.compareAge(p2); // p1.addAge(p2).addAge(p2).addAge(p2); // 链式编程 Person p = p1.addAge(p2).addAge(p2).addAge(p2); cout << p1.age << endl; cout << p.age <<endl; } int main() { test01(); system("pause"); return EXIT_SUCCESS; }
运行结果:
10 Age is unequal 120 340
代码第24行的addAge方法的返回值返回的时Person对象,函数返回时会调用Person的拷贝构造函数,所以时一个新对象。
看下面的代码:
#include <iostream> using namespace std; // this可以解决命名冲突 class Person{ public : Person(int age){ this->age = age; } Person(const Person &p){ this->age = p.age; } int age; void compareAge(Person &p) { if (this->age == p.age ){ cout << "Age is equal" << endl; } else cout << "Age is unequal" << endl; } Person & addAge(Person &p ){ this -> age += p.age; return *this; // *this 指向本体 } }; void test01() { Person p1(10); Person p2(110); cout << p1.age << endl; p1.compareAge(p2); // p1.addAge(p2).addAge(p2).addAge(p2); // 链式编程 Person p = p1.addAge(p2).addAge(p2).addAge(p2); cout << p1.age << endl; cout << p.age <<endl; } int main() { test01(); system("pause"); return EXIT_SUCCESS; }
运行结果:
10 Age is unequal 340 340
上面代码第24行,方法的返回值是引用。
补充:
看下面代码:
#include <iostream> using namespace std; class Person{ public : void show(){ cout << "Person show" << endl; } void showAge(){ cout <<m_Age << endl; } int m_Age; }; void test01() { Person *p = NULL; p ->show (); // 这句代码可以运行成功 /*p ->showAge();*/ // 涉及访问类的成员变量,而指针指向的是NULL , 无法访问成员变量 } int main() { test01(); system("pause"); return EXIT_SUCCESS; }
C++成员函数是放在公共区域的,对象只保存对象成员属性。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?