都知道static关键字是表示静态的,但有没有想过还可以如何使用static关键字呢?比如有一个这样的需求,就是在代码中有很多处要用到某一个类,但不能在每一次都用new,因为只能有一份这个类。这时用static关键字如何实现?下面就来讲讲
1.可以将类的构造函数设计成私有
2.将提供一个此类的static的引用
3.像往常一样使用类对象
具体代码如下:
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 |
// ConsoleApplication14.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> class T { private: int a; int b; T() { a = 0; b = 0; } public: static T& instace() { static T t; return t; } ~T() {} }; int main() { for (int i = 0; i < 10; i++) { T t = T::instace(); std::cout << &t << std::endl; } system("pause"); return 0; } |
测试结果:

测试结果可以看出,生成了10个t,但 实际上只有一个实例。