const修饰成员函数
[] [c++]1234567891011121314151617181920212223242526272829303132#include<bits/stdc++.h>using namespace std;class Person{public: //this指针的本质是指针常量 指向是不可以修改的 //在成员函数后面加const 修饰的是this指向 让指针指向的值也不可以修改 void showPerson() const { this->m_B=100;//特殊 //this->m_A=100; 不可修改 //this=NULL; 不可修改 } int m_A; mutable int m_B;//特殊变量 即使在常函数中也可以修改 }; void test02(){ const Person p1;//常对象 //p.m_A=100; 报错 不可以修改 p1.m_B=100; //常对象只能调用常函数 p1.showPerson(); } int main() ...
友元
全局函数做友元 其实就是声明一个函数可访问私有属性
[] [c++]123456789101112131415161718192021222324252627282930313233#include<bits/stdc++.h>using namespace std;class Building{ //全局函数做友元声明 goodgay可以访问building中私有成员 friend void goodGay(Building &building); public: string m_settingRoom; private: string m_BedRoom;};//全局函数void goodGay(Building &building){ cout<<"正在访问全局变量1"<<building.m_settingRoom<<endl; cout<<"正在访问全局变量2"<<building.m_BedRoom< ...
静态成员变量以及函数
静态成员就是在成员变量和成员函数前加上关键字static 称为静态成员也是有访问权限的 需要类内声明 类外初始化
[] [c++]1234567891011121314151617181920212223242526272829303132333435363738394041424344#include<bits/stdc++.h>using namespace std;class Person{ public: //所有对象共享同一份数据 //编译阶段就分配内存 //类内声明 类外初始化操作 static int m_A; };int Person::m_A=100;void test01(){ Person p; cout<<p.m_A<<endl;//100 Person p2; p2.m_A=200; cout<<p.m_A<<endl;//200}void test02(){ //静态成员变量不属于某个对象上 所有对象共享同一份数据 //因此静态变量有两种方 ...
类对象作为类成员
我们发现先调用的是Phone的构造函数 说明类对象作为类成员 先调用类成员的构造函数由先进后出的原则 类对象的析构函数也是最后调用的
[] [c++]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465#include<bits/stdc++.h>using namespace std;//类对象作为类成员 class Phone{public: ~Phone() { cout<<"Phone的析构函数的调用"<<endl; } Phone() { cout<<"Phone的无参构造函数的调用"<<endl; } Phone(string pName) { cout<<"Phone的有参构造函数的调用"& ...
初始化列表赋初值
十分简单 知道就行
[] [c++]123456789101112131415161718192021222324252627282930313233343536#include<bits/stdc++.h>using namespace std;class Person{ public: // 传统 //Person(int a,int b,int c) //{ // m_A=a; // m_B=b; // m_C=c; //} Person(int a,int b,int c):m_A(a),m_B(b),m_C(c){} int m_A; int m_B; int m_C;}; void test01(){ //Person p(10,20,30); 传统 Person p(10,20,30); cout<<"m_A为"<<p.m_A<<endl; cout<<"m_B为"<< ...
深拷贝与浅拷贝
如果数据开在堆上 那么浅拷贝可能出现重复释放的情况 所以我们必须学会使用深拷贝
[] [c++]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768#include<bits/stdc++.h>using namespace std;//深拷贝与浅拷贝 class Person{public: Person() { cout<<"Person默认构造函数的调用"<<endl; } ~Person() { //析构代码还可以释放堆区的数据 体现作用 if(m_Height!=NULL) { delete m_Height; m_Height=NULL;//野指针置空 } cout<<"Person析构函数的调用&qu ...