c++ --对象模型和this指针
2021/8/2 22:37:06
本文主要是介绍c++ --对象模型和this指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
对象模型和this指针
1.成员变量和成员函数分开存储
class person { public: person() { //m_a = 10; } //int m_a;//非静态成员变量占对象空间 //static int m_b;//静态成员变量不占对象空间 //void fun1() {}//函数不占对象空间 //static void fun2(){}//静态成员函数不占对象空间 }; void test01() { person p; cout << "sizeof(p)=" << sizeof(p) << endl; //当对象属性为空时,sizeof(p)=1,其他情况为4; }
2.this指针
成员对象和成员函数分开存储,为了区分成员函数被哪个对象调用,需要通过this指针解决
this指针指向被调用的成员函数所属的对象
class person { public: person(int age) { //this指针解决名称冲突(也可以将age命名为m_age) this->age = age; } person & addpersonage(person &p) { //去掉引用换成值返回 会调用拷贝构造函数 复制一个新的数据 age += p.age; //返回对象本身 return *this; } int age; }; void test01() { person p(18); cout << "年龄是" << p.age << endl; } void test02() { person p(10); person p1(10); p.addpersonage(p1).addpersonage(p1); cout << p.age << endl; }
3.空指针
//空指针也可以调用成员函数 class person { public: void fun1() { cout << "fun1调用" << endl; } void fun2() { cout << "年龄是" << this->m_age << endl; } int m_age = 10; }; int main() { person *p=NULL; //没有用到this指针,所以可以调用成员函数 p->fun1(); //p->fun2();错误,其中用到了this指针 system("pause"); return 0; }
4.常对象和常函数
class person { public: //常函数 void fun() const { //m_age = 10; m_b = 10; cout << m_b << endl; } int m_age; mutable int m_b;//加上mutable可访问 }; int main() { const person p;//常量对象 //p.m_age = 10; //常对象访问常函数 p.fun(); system("pause"); return 0; }
这篇关于c++ --对象模型和this指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-07Dify + TiDB Vector,快速构建你的AI Agent
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享