C++创建一个类(1.只能在堆上创建; 2 只能在栈上创建; 3 不能被继承(堆上和栈上都可以创建))

1 只能在堆上创建对象(不能被继承,不能再栈上创建对象)
将类的构造函数声明为private,但是为了
创建该类的对象,则必须提供创建对象和释放对象的接口,
用static函数成员实现。

#include<iostream>    
using namespace std;    
  
class HeapOnly    
{     
public:     
    static HeapOnly *CreateInstance()  
    {    
        HeapOnly * obj=new HeapOnly;    
        obj->m=2;    
        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);    
  
    //HeapOnly test; //error  
      
    system("pause");    
    return 0;    
}  
2 只能在栈上创建对象(不能在堆上创建对象)
思路:在堆上创建对象要用到new,为了在内外不能使用new,把new重载为私有
#include <iostream>    
using namespace std;    
  
class   StackOnly    
{    
public:    
    StackOnly() {   
        cout <<   "constructor."  <<   endl;  
    }    
    ~StackOnly()  
    {  
        cout << "destructor." <<   endl;     
    }    
private:    
    void*   operator   new   (size_t size);    
};    
  
int main()    
{    
    StackOnly   s;                                                     
    //StackOnly   *p   =   new   StackOnly; // error                           
      
    return   0;    
}  
3 不能被继承、能在堆上创建对象,也能在栈上创建对象
// NotInheritClass 类是不能被继承、能在堆上创建对象,也能在栈上创建对象
#include <iostream>    
using namespace std;    
  
template <typename T>   
class MakeFinal  
{  
    friend T;  
private:  
    MakeFinal() { cout << "MakeFinal "<<endl; }  
    ~MakeFinal() { cout << "~MakeFinal "<<endl; }  
};  
  
class NotInheritClass: virtual public MakeFinal<NotInheritClass>  
{  
public:  
    NotInheritClass(){ cout << "NotInheritClass "<<endl; }  
    ~NotInheritClass(){ cout << "~NotInheritClass "<<endl; }  
};  
  
  
// class Test:public NotInheritClass // 继承失败  
// {  
// public:  
//  Test(){};  
//  ~Test(){};  
// };  
  
int main()  
{     
    NotInheritClass test1;  
    NotInheritClass *test2 = new NotInheritClass;  
    delete test2;  
    return 0;  
}  
  
// 由于类 NotInheritClass 是从类 MakeFinal <NotInheritClass> 虚继承过来的,  
// 在调用 Test 的构造函数的时候,  
// 会直接跳过 NotInheritClass 而直接调用 MakeFinal <NotInheritClass> 的构造函数。  
// 非常遗憾的是, Test 不是 MakeFinal <NotInheritClass> 的友元,  
// 因此不能调用其私有的构造函数。  
// 基于上面的分析,试图从NotInheritClass 继承的类,一旦实例化,  
// 都会导致编译错误,因此NotInheritClass 不能被继承。这就满足了我们设计要求。  



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值