只有非静态成员变量才属于类的对象上
#includeusing namespace std; class Person1 { }; class Person2 { int A; }; class Person3 { static int A; }; class Person4 { void show1(){} }; class Person5 { static void show2() {} }; void test01() { Person1 p; cout << "一个空对象的内存字节为:" << sizeof(p) << endl; } void test02() { Person2 p; cout << "一个对象(一个int变量)的内存字节为:" << sizeof(p) << endl; } void test03() { Person3 p; cout << "一个对象(一个静态成员变量)的内存字节为:" << sizeof(p) << endl; } void test04() { Person4 p; cout << "一个对象(一个函数)的内存字节为:" << sizeof(p) << endl; } void test05() { Person5 p; cout << "一个对象(一个静态函数)的内存字节为:" << sizeof(p) << endl; } int main() { test01(); test02(); test03(); test04(); test05(); system("pause"); return 0; }
一个空对象的内存字节为:1
一个对象(一个int变量)的内存字节为:4
一个对象(一个静态成员变量)的内存字节为:1
一个对象(一个函数)的内存字节为:1
一个对象(一个静态函数)的内存字节为:1
总结:当对象中没有非静态变量时,编译器会给它一个字节的内存空间,防止它与其他的占用同一块空间,静态成员变量和函数都不属于类的对象上,不占用内存空间
this指针概念每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码
C++通过特殊的对象指针(this指针)来区分哪个对象调用自己的,this指针指向被调用的成员函数所属的对象
this指针是隐含每一个非静态成员函数内的一种指针
this指针不需要定义,直接使用即可
this指针的用途:
当形参和成员变量同名时,可用this指针来区分
当类的非静态成员函数中返回对象本身,可用return *this
#includeusing 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); cout << "p1的年龄为:" << p1.age << endl; } //返回对象本身用this void test02() { Person p1(18); Person p2(18); p1.PersonAddAge(p2); cout << "p1的年龄为:" << p1.age << endl; //链式编程思想 p1.PersonAddAge(p2).PersonAddAge(p2).PersonAddAge(p2); cout << "p1的年龄为:" << p1.age << endl; } int main() { test01(); test02(); system("pause"); return 0; }
空指针访问成员函数p1的年龄为:18
p1的年龄为:36
p1的年龄为:90
空指针也可以调用成员函数,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
#includeusing namespace std; class Person { public: void showClassName() { cout << "this is Person class" << endl; } void showPersonAge() { if (this == NULL) { return; } //报错原因是因为传入的指针是NULL cout << "age = " << this->m_Age << endl; } int m_Age; }; void test01() { Person* p = NULL; p->showClassName(); p->showPersonAge(); } int main() { test01(); system("pause"); return 0; }
const修饰成员函数this is Person class
常函数:
- 成员函数后加const后我们称这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数
#includeusing namespace std; class Person { public: //this指针的本质是指针常量 指针的指向不可以改变 //在成员函数后面加const 修饰的是this指针,让this指向的值也不可以改变 //常函数 void showPerson() const { //this = NULL; //this->m_Age = 100; const Person * const this this->B = 10; } int m_Age; mutable int B;//特殊变量 即使在常函数中也可以修改值 }; void test02() { //常对象 const Person p; //常对象只能调用常函数 p.showPerson(); //p.m_Age = 100; p.B = 1000;//B是特殊变量在常对象下也可以修改 } void test01() { Person p; } int main() { test01(); test02(); system("pause"); return 0; }



