-
函数返回的是this指针的解引用,也就是被调用函数的对象。
-
例如c++的输出函数 cout,它可以无限追加,这就是链式编程思想
cout << "hello" << "world" << "Tony" <
-
采用链式编程思想的函数的返回值是引用,即对象本身,而非值拷贝
-
示例-返回值为引用
#include
#include #include #include using namespace std; class Person { public: Person(int age):m_age(age) {} Person& PersonAddAge(Person &p) { this->age += p.age; //this指向p2的指针,而*this指向的是p2这个对象的本体 return *this; } int m_age; }; void test() { Person p1(10); cout << "p1的年龄为:"< test(); cout << "program run finish!" << endl; return 0; } 运行结果:
p1的年龄为:10 p2的年龄为:40 program run finish!
-
示例-返回值为对象
#include
#include #include #include using namespace std; class Person { public: Person(int age):m_age(age) {} Person PersonAddAge(Person &p) { this->age += p.age; //this指向p2的指针,而*this指向的是p2这个对象的本体 return *this; } int m_age; }; void test() { Person p1(10); cout << "p1的年龄为:"< test(); cout << "program run finish!" << endl; return 0; } 运行结果:
p1的年龄为:10 p2的年龄为:20 program run finish!
-
返回值为对象引用
返回的是对象本身,在对象本身上连续增加3次年龄,所以是40.
-
返回值为对象
此函数 return *this 返回时,由于此函数返回值类型是对象,所以此处会创建一个临时对象,相当于:
Person temp; temp = *this;
在p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1) 操作中
-
只有第一个PersonAddAge(p1)对p2的年龄进行了加10操作,为20岁,且创建临时变量temp,进行值拷贝,此时temp的年龄也为20岁
-
第二个PersonAddAge(p1)是给临时变量temp增加十岁,此时temp的年龄为30岁,同时第三个temp1,进行值拷贝,此时temp1的年龄同temp一样,也为30岁
-
第三个PersonAddAge(p1)是给临时变量temp1增加十岁,此时temp1的年龄为40岁,同时第三个temp2,进行值拷贝,此时temp2的年龄同temp1一样,也为40岁
-
最终p2的年龄只在第一次PersonAddAge(p1)时增加了十岁而已,为20岁。
-



