在上一节中,我们知道每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码区域。
C++通过提供特殊的对象指针:this指针,解决上述问题。
看一段代码:
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
age = age;
}
int age;
};
int main()
{
Person p(18);
cout << "年龄是:" << p.age << endl;
system("pause");
return 0;
}
在Person类中,含参构造函数中三个age,三个age是同一个age,因此解决方法:
- 对于类内成员都添加m_区分,表明是类内成员(member)。
- 添加this->。this->age = age;
// this指针指向的是:被调用的成员函数所属的对象。谁调用成员函数,它就是谁。谁调用的有参构造,p,因此this就指向调用者p。
#include<iostream>
#include "07this指针的用法.h"
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
void PersonAddAge(Person& p)
{
this->age += p.age;
}
int age;
};
void test01()
{
Person p(18);
cout << "年龄是:" << p.age << endl;
}
void test02()
{
Person p1(10);
Person p2(18);
p2.PersonAddAge(p1);
cout << "p2加p1之后的年龄为:" << p2.age << endl; // 28。
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
高潮:
更进一步,再加的情形。链式编程思想。
#include<iostream>
#include "07this指针的用法.h"
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
Person& PersonAddAge(Person& p) // 引用的方式返回本体。
{
this->age += p.age;
return *this;
}
int age;
};
void test01()
{
Person p(18);
cout << "年龄是:" << p.age << endl;
}
void test02()
{
Person p1(10);
Person p2(18);
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p2); // 链式编程思想。无限往后追加。cout中的<< 也是如此。
cout << "p2加p1之后的年龄为:" << p2.age << endl; // 76
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
一定要注意返回的是本体的引用,如果不写&,那么结果就不一样了。
#include<iostream>
#include "07this指针的用法.h"
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
Person PersonAddAge(Person& p) // 引用的方式返回本体。
{
this->age += p.age;
return *this;
}
int age;
};
void test01()
{
Person p(18);
cout << "年龄是:" << p.age << endl;
}
void test02()
{
Person p1(10);
Person p2(18);
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p2); // 链式编程思想。无限往后追加。cout中的<< 也是如此。
cout << "p2加p1之后的年龄为:" << p2.age << endl; // 28
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
返回值为28。为何?