【c++】设计特殊的类

设计一个特殊的类,该类只能在堆上创建对象

将类的析构函数声明为private,但是为了创建该类的对象,则必须提供创建对象和释放对象的接口,用static函数成员实现:

class HeapOnly
{
public:
    static HeapOnly *CreateInstance()
    {
        HeapOnly *obj = new HeapOnly;
        obj->m = 9;
        return obj;
    }
    static void DeleteInstance(HeapOnly *obj)
    {
        if (obj != NULL)
            delete obj;
    }
private:
    HeapOnly(){};
    ~HeapOnly(){};
public:
    int m;
};

int main()
{
    HeapOnly *obj = HeapOnly::CreateInstance();
    cout << obj->m << endl;
    HeapOnly::DeleteInstance(obj);
    system("pause");
    return 0;
}
设计一个类,该类只能在栈上创建对象

在堆上创建对象要用到new,为了在类外不能使用new,delete,把new,delete重载为私有:

class StackOnly
{
public:
    StackOnly()
    {
        cout << "constructor." << endl;
    }
    ~StackOnly()
    {
        cout << "destructor." << endl;
    }
private:
    void* operator new(size_t size);
    void operator delete(void* ptr);
};
int main()
{
    StackOnly s;
    system("pause");
    return 0;
}
设计一个类,该类只能创建一个对象

类实例化对象时,需要检查是否已经存在同类对象,所以需要静态成员变量;另外还要提供对外的全局访问方式,故需要静态方法来创建与销毁该实例对象:

class singleton
{
public:
    static singleton* getpsin()
    {
        if (psin == NULL)
        {
            psin = new singleton();
        }
        return psin;
    }
    static void relice()
    {
        if (psin != NULL)
        {
            delete psin;
        }
        psin = NULL;
    }
private:
    singleton()
    {
        cout << "+++++" << endl;
    }
    static singleton* psin;
};

singleton* singleton::psin = NULL;
int main()
{
    singleton *p = singleton::getpsin();
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值