c++——对象模型和this指针
1.成员变量和成员函数分开储存
在c++中类内的成员变量和成员函数分开储存,只有非静态的成员变量才属于类的对象上
c++编译器会给每个空对象也分配一个内存空间,是为了区分空对象占内存的位置
this指针是隐含每一个非静态成员函数内的一种指针
this指针不需要定义,直接使用即可
this指针指向被调用的成员函数所属的对象
this指针的用途
- 当形参和成员变量同名时,可用this指针来区别
- 在类的非静态成员函数中返回对象本身 可使用 return *this
#include<iostream> #include<string> using namespace std; class person { public: person(int age) { //this指向被调用的成员函数所属的对象 this->age = age; } person& personaddperson(person& p) { this->age += p.age; return *this; } int age; }; //1.解决名称冲突 void test01() { person p1(18); cout << "p1的年龄" << p1.age << endl; } //2.返回对象本身用*this void test02() { person p1(10); person p2(10); p2.personaddperson(p1).personaddperson(p1); cout << "p2:" << p2.age << endl; } int main() { test01(); test02(); }
浙公网安备 33010602011771号