青岛高品质网站建设,网站布局模版,晋江建设银行招聘网站,做网站用百度浏览器目录 1.成员变量和成员函数分开存储
2.this指针
1.this指针概念
编辑
2.this指针用途
3.空指针访问成员函数
编辑
4.const修饰成员函数 mutable声明
1.成员变量和成员函数分开存储 空对象占用内存空间为1字节#xff0c;这样是为了区分不同的空对象占内存的位置 …目录 1.成员变量和成员函数分开存储
2.this指针
1.this指针概念
编辑
2.this指针用途
3.空指针访问成员函数
编辑
4.const修饰成员函数 mutable声明
1.成员变量和成员函数分开存储 空对象占用内存空间为1字节这样是为了区分不同的空对象占内存的位置
使得每个空对象都有一个独一无二的内存地址
代码示例
#includebits/stdc.h
using namespace std;
using ll long long;class stu
{};class person
{int a;static int b;
};int person::b 100;int main(){person p;stu s;cout sizeof(s) endl;cout sizeof(p);return 0;
}2.this指针
1.this指针概念 谁调用函数this指针就指向它
this指针不需要定义直接使用
2.this指针用途 代码示例
#includebits/stdc.h
using namespace std;class person
{public:int age;// person(int age){// age age;// }错误的编译器会认为这三个age是同一个person(int age){this - age age;//解决了名称冲突}//这里要以引用的方式返回//如果不这样就是以值的方式返回会复制一个新的对象而不是原来的p1person personaddage(person p){this - age p.age;//此时this是指向p1的指针//*this就是p1return *this;}
};int main(){person p1(18);cout p1年龄为 p1.age endl;person p2(10);p1.personaddage(p2).personaddage(p2);cout p1年龄为 p1.age endl;return 0;
}3.空指针访问成员函数 代码示例
#includebits/stdc.h
using namespace std;class person
{public:int age;void show(){cout Here is class person endl;}void showage(){if(this NULL) return;//提高代码健壮性防止为空的情况cout age endl;//相当于cout this - age endl;}
};int main(){person *p NULL;p - show();p - showage();return 0;
}4.const修饰成员函数 mutable声明
代码讲解
#includebits/stdc.h
using namespace std;class person
{public://this指针本质上是person * const this指针常量指向不可以修改//指向的值可以修改void func(int c) const{//这里的const修饰的是this指向让this指向的值也不可以修改//相当于从person * const this变为const person * const thisa c;}mutable int a 0;//mutable声明使得在常函数和常对象中也可以修改这个值int b 6;};int main()
{const person p;//常对象//p.b 5;错误的常对象不可修改属性p.a 20;cout p.a endl;p.func(19);cout p.a endl;return 0;
}这里使用const person p时一定要给a和b赋初值不然会报错说未初始化