
静态成员变量和静态成员函数
静态成员变量
编译阶段分配内存
所有对象共享内存
通过对象访问,通过类名访问
有权限控制
类内进行声明,类外进行初始化
静态成员函数
不可以访问普通成员变量,可以访问静态成员变量
普通成员函数都可以访问
静态成员函数也有权限
通过对象访问,通过类名访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
using namespace std;
class { private: static int m_other; public: Person(); ~Person();
static int m_Age;
static void func() { cout<<"func调用"<<endl; }
};
int Person::m_Age = 0; int Person::m_other =0; Person::Person() {
}
Person::~Person() {
}
void test() { Person p1; p1.m_Age = 10;
Person p2; p2.m_Age = 20;
cout<<"p1: "<<p1.m_Age<<endl; cout<<"p2: "<<p2.m_Age<<endl;
cout<<"通过类名访问: "<<Person::m_Age<<endl;
p1.func(); p2.func(); Person::func();
} int main(void) {
test(); return 0; }
|
单例模式案例
主席案例
目的 为了让类中只有一个实例,实例不需要自己释放
将 默认构造 和 拷贝构造 私有化
内部维护一个 对象指针
私有化唯一指针
对外提供 getinstance 方法来访问这个指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
using namespace std;
class ChairMan { private: ChairMan(); ChairMan(const ChairMan&c); static ChairMan * singleMan; public: static ChairMan *getInstance() { return singleMan; } ~ChairMan(); };
ChairMan::ChairMan() { cout<<"创建国家主席"<<endl; }
ChairMan::~ChairMan() { }
ChairMan * ChairMan::singleMan = new ChairMan;
void test() { ChairMan *cm1 = ChairMan::getInstance(); }
int main(void) { cout<<"Main函数调用"<<endl; test(); return 0; }
|
打印机案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
using namespace std;
class Printer { private: Printer(){ m_count =0;} Printer(const Printer &p){}
int m_count;
static Printer *singlePrinter; public:
static Printer *getInstance() { return singlePrinter; }
void printText(string text) { m_count++; cout<<text<<endl; cout<<"打印机使用了"<<m_count<<"次"<<endl; } ~Printer(){} };
Printer * Printer::singlePrinter = new Printer;
void test() { Printer *printer = Printer::getInstance();
printer->printText("离职报告"); printer->printText("入职报告"); } int main(void) { test(); return 0; }
|
C++对象模型初探
成员变量和成员函数分开存储
空类的大小为 1
只有非静态成员变量才属于对象身上,且计算大小按字节对齐
普通成员函数、静态成员函数和静态成员变量都不属于对象身上
this指针的使用
指针永远指向当前对象
解决命名冲突
*this 指向对象本体
非静态的成员函数才有this指针
空指针访问成员函数
如果成员函数没有用到this,那么空指针可以直接访问
如果成员函数用的this指针,就用注意,可以加if判断,如果this为NULL就return
常函数、常对象
常函数 void func() const {} 常函数
常函数修饰this指针 const Type *const this
常函数 不能修改this指针执行的值
常对象 在对象前加入const修饰 const Person p1
常对象 不可以调用普通的成员函数
常对象可以调用常函数
用mutable修饰的关键字是在常函数可以修改的
友元
全局函数做友元函数
全局函数写到类中做声明,并且在最前面加上关键字friend
整个类做友元类
firend class 类名
友元的是单向的、不可传递的
成员函数做友元函数
friend void 类名::成员函数();
近期评论