好吧, 第一次见这种单例, 来瞧瞧:
#include <iostream>
using namespace std;
class A
{
private:
A() // 之所以设置为private, 是因为为了防止外部直接生成对象
{
cout << "A" << endl;
}
public:
// 看到这种单例, 也是醉了。 不管咋样, 又多知道了一种方式
static A* getInstance()
{
static A a;
return &a;
}
void print()
{
cout << "hello world" << endl;
}
};
int main()
{
A::getInstance()->print();
A::getInstance()->print();
A::getInstance()->print();
return 0;
}
结果:
A
hello world
hello world
hello world