C++ 面向对象 类和对象-c++对象模型和this指针
2021/9/19 12:05:21
本文主要是介绍C++ 面向对象 类和对象-c++对象模型和this指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream> using namespace std; class Person { int m_A;//非静态成员变量 属于类的对象上的 static int m_B;//静态成员变量 不属于类的对象上 void func(){}//非静态成员函数 static void func2(); }; int Person::m_B = 0; void test01() { Person p; //空对象占用内存空间为 1 //c++编译器会给每个空对象也分配一个字节空间,是为了区分空对象栈内存的位置 //每个空对象也应该有一个独一无二的内存地址 cout << "size of p=" << sizeof(p) << endl; } void test02() { Person p; cout << "size of p=" << sizeof(p) << endl; } int main() { test01(); system("pause"); return 0; }
#include <iostream> using namespace std; class Person { public: Person(int age) { //this 指针指向 被调用的成员函数所属的对象 this->age = age; } //若想返回本体 ,需要返回一个引用的形式 Person& PersonAddAge(Person &p) { this->age += age; return *this;// this 指针指向p2的指针 而*this指向的就是p2这个对象的本体 } int age; }; //解决名称冲突 void test01() { Person p1(18); 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() { test02(); system("pause"); return 0; }
#include <iostream> using namespace std; class Person { public: void showClassName() { cout << "this is Person class" << endl; } void showPersonAge() { if (this == NULL) { return;//return 掉 } //报错的原因是因为传入的指针为NULL this 指向test01 中的*P对象,而*p又是空; 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; }
这篇关于C++ 面向对象 类和对象-c++对象模型和this指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享