c++中类内成员变量和成员函数分开存储 只有非静态成员变量才属于类的对象上 空对象内存大小为1个字节 区分空对象占内存的位置
每一个静态函数只会诞生一份函数实例 多个同类型的对象会共用一块代码 如何区分呢 this指针指向被调用的成员函数所属的对象 其隐含每一个非静态成员函数内 无需定义直接使用
所以当形参与成员变量同名时 可用this指针来区分 在类的非静态成员函数中返回对象本身 可使用return *this
[] [c++] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include<bits/stdc++.h> using namespace std; class Person { public: Person(int age) { //this指向被调用的成员函数的所属对象 //也就是谁调用的这个有参构造 就指向谁 this->age=age; } Person& PersonAddAge(Person &p)//必须引用 否则调用拷贝构造函数 { this->age+=p.age; //this指向p2的指针 *this指向的就是p2这个对象本体 return *this; } int age; }; //1.解决名称冲突 void test01() { Person p1(18); //this指向了p1 cout<<"p1年龄为"<<p1.age<<endl; } //2.返回对象本身用*this void test02() { Person p1(10); Person p2(10); p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); cout<<"p2的年龄为:"<<p2.age<<endl; } int main() { //test01(); test02(); return 0; }
空指针调用成员函数 传入指针为NULL 不能访问属性
[] [c++] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include<bits/stdc++.h> using namespace std; class Person { public: void showClassName() { cout<<"this is Person class"<<endl; } void showPersonAge() { //报错原因是传入的指针为NULL if(this==NULL) return; cout<<"age为"<<this->m_Age<<endl; } int m_Age; }; int main() { Person *p=NULL; p->showClassName(); p->showPersonAge(); return 0; }