注意:
- 静态对象中可以包含非静态函数和非静态成员数据。
代码:
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton& getInstance(int var) {
static Singleton instance(var);
cout << "called." << endl;
return instance;
}
int getvalue() {
return m_a;
}
int setvalue(int var) {
m_a = var;
}
private:
int m_a;
private:
Singleton(int a) : m_a(a) { };
~Singleton() { };
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
};
int main()
{
static Singleton& x = Singleton::getInstance(5100);
cout << "&x : " << &x << endl;
cout << "x.m_a : " << x.getvalue() << endl;
x.setvalue(10000);
cout << "x.m_a : " << x.getvalue() << endl;
static Singleton& y = Singleton::getInstance(5100);
cout << "&y : " << &y << endl;
return 0;
}
执行结果:
[root@localhost 09_static]# ./a.out
called.
&x : 0x6021e8
x.m_a : 5100
x.m_a : 10000
called.
&y : 0x6021e8