qfedu-cpp-level/day4/d2.cpp

54 lines
1.0 KiB
C++
Raw Normal View History

// 类的单例设计模式
// 私有化构造函数和拷贝函数, 提供一个public的静态函数返回类的指针对象 声明一个静态的类
// 的指针对象。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class A // 单例的类: 类的对象运行期间有且只有一个对象
{
private:
int x;
A(int x) { this->x = x; }
A(const A &other)
{
x = other.x;
}
public:
static A *getInstance(int x = 0)
{
if (instance == NULL)
{
instance = new A(x);
}
return instance;
}
void show()
{
cout << "x = " << x << endl;
}
public:
static A *instance;
};
A *A::instance = NULL; // 定义初始化,在静态全局区
int main()
{
A *a1 = A::getInstance(20);
a1->show();
A *a2 = A::getInstance();
a2->show();
cout << "a1 addr = " << a1 << endl;
cout << "a2 addr = " << a2 << endl;
delete A::instance; // 释放单例对象的空间
return 0;
}