您的位置:首页 > 编程语言 > C语言/C++

C++的Singleton模式实现

2011-04-05 10:16 316 查看
Singleton.h

class A {
private:
static A *_instance;
protected:
A();
public:
static A* getInstance();
void sayhello();
};

Singleton.cpp

#include <iostream>
#include "singleton.h"
using namespace std;

A* A::_instance = 0;

A::A() {}
A* A::getInstance() {
if (_instance == 0)
_instance = new A;
return _instance;
}
void A::sayhello() {
cout << "Hello!" << endl;
}

testsingleton.cpp

#include "singleton.h"
#include <iostream>
using namespace std;

int main()
{
A *abc = A::getInstance();
abc->sayhello();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: