禁止在栈中初始化的类【2】

    将构造和析构设置为private,即可禁止栈中实例化。如果用protected,则可以被继承。

   

// 禁止在栈中实例化。那就只有在堆中实例化喽?
// 在栈中实例化需要干嘛呢?构造和析构。将其中之一设为private即可。
// 然后就是单件模式的套路了~在成员函数中提供接口,执行new和delete操作。
// PS:将构造和析构设计为私有,同时也就禁止了继承。
// 但是如果设计为protected可以实现继承,不过会不会留下隐患?子类可以使用共有构造和析构函数,这样可以拥有父类的行为
#include <iostream>
using namespace std;

class S   // 标准单件模式1
{
public:
    static S* get_instance()
    {
        if(sp) return sp;
        else   return (sp=new S);
    }
    void print(){cout<<"It is S"<<endl;}
    void destroy()
    {
        delete this;
    }
private:
    static S*sp;
    S(){cout<<"S::ctor"<<endl;}
    ~S(){cout<<"S::dector"<<endl;}
};

S* S:: sp=0;

class S2   // 标准单件模式2
{
public:
    static S2* get_instance()
    {
        static S2 s;
        return &s;
    }
    void print(){cout<<"It is S2"<<endl;}
    void destroy()
    {
        ;
    }
private:
    S2(){cout<<"S2::ctor"<<endl;}
    ~S2(){cout<<"S2::dector"<<endl;}
};

// 构造和析构声明为protected,这样禁止在栈中构造,但是不影响继承。
class Parent
{
public:
    void print(){cout<<"It is Parent"<<endl;}

protected:

    Parent(){cout<<"Parent::ctor"<<endl;}
    ~Parent(){cout<<"Parent::dector"<<endl;}
};


class child:public Parent   // child中除了共有的构造和析构以外什么也没有
{
public:
    child(){cout<<"child::ctor"<<endl;}    
    ~child(){cout<<"child::dector"<<endl;}    
};
int main()
{
    {
        S*p= S::get_instance();  // 用指针的单件模式
        p->print();
        p->destroy();
    }
    cout<<endl<<endl;
    {
        S2*p= S2::get_instance();  //用static变量的单件模式
        p->print();

    }   
    cout<<endl<<endl;
    
    child chld;                   // 继承之后,等效于在栈中实例化了Parent
    Parent &rp=chld;
    rp.print();
    return 0;
}

chen@chen-book1:~$ g++ heap_only.cpp -o heaponly
chen@chen-book1:~$ ./heaponly 
S::ctor
It is S
S::dector


S2::ctor
It is S2


Parent::ctor
child::ctor
It is Parent                  // !!!!
child::dector
Parent::dector
S2::dector
chen@chen-book1:~$ 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值