-
采用链式编程思想的函数的返回值是引用,即对象本身,而非值拷贝
-
示例-返回值为引用
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
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的年龄为:"<<p1.age << endl;
Person p2(10);
//链式编程思想
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout << "p2的年龄为:"<<p2.age << endl;
}
int main()
{
test();
cout << "program run finish!" << endl;
return 0;
}
运行结果:
p1的年龄为:10
p2的年龄为:40
program run finish!
-
示例-返回值为对象
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
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的年龄为:"<<p1.age << endl;
Person p2(10);
//链式编程思想
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout << "p2的年龄为:"<<p2.age << endl;
}
int main()
{
test();
cout << "program run finish!" << endl;
return 0;
}
运行结果:
p1的年龄为:10
p2的年龄为:20
program run finish!