c++成员变量和成员函数是分开存储的
每一个非静态成员函数只会诞生一份函数实例,同类型的对象会公用一份代码
this指针指向被调用的成员函数所属的对象
- this指针是隐含每一个非静态成员函数的一种指针
- this指针不需要定义,直接使用即可
用途:
- 形参和成员变量重名时,可以用this指针来区分;
- 在类的非静态成员 函数中返回对象本身,可使用return *this;
#include<iostream>
using namespace std;
#include<string>
//this指针
//1.解决对象冲突
class person
{
public:
//当形参和成员变量同名时,可用this指针来进行 区分
person(int age)
{
this->age = age;
}
int age;
};
void test01()
{
person p1(10);
cout << "p1的age=" << p1.age << endl;
}
int main()
{
test01();
cout << "程序运行结束" << endl;
system("pause");
return 0;
}
#include<iostream>
using namespace std;
#include<string>
//this指针
//2.返回对象本身
class person
{
public:
person(int age)
{
this->age = age;
}
person& personAdd(person &p)
{
this->age += p.age;
return *this;//返回函数本体
}
int age;
};
void test01()
{
person p1(10);
person p2(10);
p2.personAdd(p1).personAdd(p1).personAdd(p1);
cout << "p2的age=" << p2.age << endl;
}
int main()
{
test01();
cout << "程序运行结束" << endl;
system("pause");
return 0;
}