C++学习笔记day-13-C++对象类型和this指针
2020-07-23 10:00
197 查看
1、成员变量和成员函数分开存储
#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() { test02(); system("pause"); return 0; }
2、this指针的使用
#include<iostream> using namespace std; class Person { public: Person(int age) { 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; } //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; }
3、空指针调用成员函数
#include<iostream> using namespace std; //空指针调用成员函数 class Person { public: //this指针的本质是指针常量,指针的指向不可以修改 //相当于Person *const this; //在成员函数后面加const,修饰的是this指向,让指针只晓得值也不可以修改 void showPerson()const//相当于const Person *const this { //this =NULL;//this 指针不可以修改指针的指向的 cout << "this is Person class" << endl; } void func(){} //void showPersonAge() //{ // //报错原因是因为传入的指针为NULL // cout << "age= " <<this-> m_Age << endl; //} //int m_Age; int m_A; mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值,加上关键字 }; void test01() { Person p; p.showPerson(); } //常对象 void test02() { const Person p;//在对象前加const,变为常对象 //p.m_A = 100; p.m_B = 100;//m_B特殊值,在常对象下也可以修改 //常对象只能调用常函数 p.showPerson(); //p.func();//常对象不可以调用普通成员函数,因为普通成员函数可以修改属性。 } int main() { test01(); system("pause"); return 0; }
相关文章推荐
- C++学习笔记(八)(C++对象模型和this指针 ,友元)
- C++学习笔记(13)——利用对象、引用、指针调用虚函数
- C++学习笔记(13)——利用对象、引用、指针调用虚函数
- C++学习笔记(六)-- 类和对象 构造函数和析构函数 const成员函数 this指针 对象数组 堆栈管理变量
- C++学习笔记之八 复合类型---指针、数组和指针运算
- C++学习笔记(八):函数重载、函数指针和函数对象
- VS2010 C++ 学习笔记(六) this指针 const 指针 引用
- C++学习笔记之数据类型(2)数组、向量、指针
- [C++学习笔记14]动态创建对象(定义静态方法实现在map查找具体类名对应的创建函数,并返回函数指针,map真是一个万能类)good
- C++ 学习笔记(2)变量和基本类型(复合类型:引用、指针)、const、constexpr、typedef(using)、auto、decltype
- c++对象模型笔记:指针类型转换
- 【C++学习笔记】13_指针的运算
- C++ Prime学习笔记之this指针
- Delphi 2010学习笔记(13)---数据类型(指针)---2011-01-20
- JAVA学习笔记3--类,对象,变量,方法,构造方法,this,引用类型
- C++ 学习笔记(19)new/delete表达式、定位new、typeid、dynamic_cast、type_info、枚举类型、成员函数指针、union、位域、volatile限定符、链接指示
- 【C++】学习笔记草稿版12(类对象的类型转换)
- c++ 学习笔记(高级linux编程) day13
- 【C++学习笔记】this指针
- C++学习笔记-const对象,类型别名,auto和decltype