#include <iostream>
//单例模式
/*
C++中的单例模式通常是通过对构造函数设置为private来实现
*/
using namespace std;
class world
{
world()
{
//私有的构造函数,只能由类的成员函数来获取实例
}
public:
static world *getInstance();
/*
static函数也是类函数,所以在写定义时也要写明属于哪个类。与不同类函数不同的是,
它没有传入this指针,正因为没有this指针,所以static类成员函数不能访问非static的
类成员,只能访问 static修饰的类成员。
*/
void show(); //show里面要用到instance指针,就必须要把实现写在后面,因为会要求申明顺序
};
static world *instance = nullptr;
world *world::getInstance() //必须在类外实现,否则会提示找不到符号:undefined reference to ...,并且不用加static
{
if (instance == nullptr)
{
instance = new world;
}
return instance;
}
void world::show()
{
cout << "ptr:" << hex <<instance << endl;
}
int main()
{
world *a = world::getInstance(); //使用类中的static来获取单个实例
world *b = world::getInstance(); //虽然是两个world对象,但是最终只会有一个world实例被创造出来
a->show();
b->show();
//运行程序,就会看到即使我运行了两次getInstance,实际上的对象只生成了一份
}
方法2:
class D{
private:
D(){cout<<"D has created!"<<endl;} //首先,构造函数设置为private
public:
static D& init(){ //然后
static D obj_only_1;
return obj_only_1;
}
};
D obj1=D::init();
D obj2=D::init();
D obj3=D::init(); //在这里可以看到,即使我申请了3个D对象,调用了3次init函数,但是只会调用一次D的构造函数,即:只输出一条“D has created!”
//这就是大名鼎鼎的单例模式
return 0;