当类不想被继承时:将构造函数和析构函数私有化

参考博客:
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值