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++成员函数是放在公共区域的,对象只保存对象成员属性。