java单例模式的类能否被继承_C++无法被继承的类实现以及单例模式的类的实现...

无法被继承的类的实现

思路

构造函数是类的私有成员函数,同时在共有成员函数里,声明创建该类的实例的函数。以及释放该类的析构函数。

范例

#include

using namespace std;

class A

{

public:

static A * Construct(int n)

{

A *pa = new A;

pa->num = n;

cout << "num is:" << pa->num << endl;

return pa;

}

static void Destruct(A * pIntance)

{

delete pIntance;

pIntance = NULL;

}

private:

A(){}

~A(){}

public:

int num;

};

class B:public A//如果后面声明一个B的实例,则报错

{

};

void main()

{

A *f = A::Construct(9);

cout << f->num << endl;

A::Destruct(f);

// B b;//error error: ‘A::A()’ is private

}

上面这个类不可以实现在栈上创建对象。也就是说,仅仅只可以在堆上构建任何的一个对象,而在栈上就无能为力了。

私有的构造函数极大的局限性就这样一览无余了。(其实,上面类设计即是一种只可以创建堆对象,不可以创建栈对象的情况。

i

a在栈上建立一个类的对象,需要使用下面的方法:

#include

using namespace std;

template

class Base

{

friend T;

private:

Base() {}

~Base() {}

};

class Finalclass : virtual public Base

{

public:

Finalclass() {}

~Finalclass() {}

};

class TestClass : public Finalclass

{

};

int main()

{

Finalclass* p = new Finalclass; // 堆上对象

Finalclass fs; // 栈上对象

// TestClass tc; // 基类构造函数私有,不可以被继承。因此不可以创建栈上对象。

return 0;

}

当派生类TestClass在构造对象时,因为是虚继承,所以派生类TestClass的构造函数会直接去调用Base基类的构造函数,而Base的构造函数是私有的。编译错误!

单例模式

#include

using namespace std;

class CSingleton

{

private:

CSingleton() //构造函数是私有的

{

}

static CSingleton *m_pInstance;

public:

static CSingleton * GetInstance()

{

if(m_pInstance == NULL) //判断是否第一次调用

m_pInstance = new CSingleton();

return m_pInstance;

}

};

CSingleton *CSingleton ::m_pInstance=NULL;//一定要初始化

int main()

{

CSingleton* p0 = CSingleton :: GetInstance();

CSingleton* p1 = CSingleton :: GetInstance();

CSingleton* p2 = p1->GetInstance();

CSingleton & ref = * CSingleton :: GetInstance();

cout<

cout<

cout<

cout<

return 0;

}

另外测试

#include

using namespace std;

class CSingleton

{

private:

CSingleton() { cout<

static CSingleton *m_pInstance;

class CGarbo

{

public:

~CGarbo()

{

cout<

if(CSingleton::m_pInstance)

{

delete CSingleton::m_pInstance;

cout<

}

}

};

static CGarbo Garbo;

public:

static CSingleton * GetInstance()

{

cout<

if(m_pInstance == NULL)

{

cout<

m_pInstance = new CSingleton();

}

return m_pInstance;

}

};

CSingleton* CSingleton ::m_pInstance=NULL;

CSingleton::CGarbo CSingleton::Garbo;

class aclass{

public:

int c;

static int a;

static void fun(){cout<

void fun2(){cout<

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值