参考博客:
https://www.cnblogs.com/Rosanna/p/3339823.html
#include
using namespace std;
class Base
{
private:
Base() {};
~Base() {};
public:
int num;
static Base* Construct()
{
return new Base;
}
static Base* Construct(int n)
{
Base* p = new Base;
p->num = n;
cout << “num is:” << p->num << endl;
return p;
}
static void Destruct(Base* instance)
{
delete instance;
instance = NULL;
}
};
class Base1 :public Base
{
public:
//error, 当子类构造函数调用时会先调用父类的构造函数,但是父类的构造函数是私有的,访问不了
Base1()
{
cout << “Base1” << num;
}
};
int main()
{
Base* b1;
Base* b2 = Base::Construct(9);
Base* b3 = Base::Construct(10);
cout << b2 << " " << b3 << endl;
Base::Destruct(b2);
Base::Destruct(b3);
return 0;
}
单例模式的实现:
参考博客:单例模式
#include
using namespace std;
class Singleon
{
private:
Singleon()
{
//instrance = NULL;
cout << “Singleon()” << endl;
}
static Singleon* instance;
public:
static Singleon* GetSingleon()
{
if (NULL == instance)
{
instance = new Singleon();
cout << “对象创建成功” << endl;
}
else
{
cout << “对象已经创建成功,无须再建” << endl;
}
return instance;
}
static void Destroy()
{
cout << “destroy” << endl;
delete instance;
instance = NULL;
//return instance;
}
};
Singleon* Singleon::instance = NULL;
int main()
{
Singleon* sl1 = Singleon::GetSingleon();
Singleon* sl2 = Singleon::GetSingleon();
Singleon* sl3 = Singleon::GetSingleon();
cout << sl1 << endl;
cout << sl2 << endl;
cout << sl2 << endl;
sl1->Destroy(); //需要手动释放内存
system(“pause”);
return 0;
}