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

来源:互联网 发布:c语言代码图片 编辑:程序博客网 时间:2024/06/05 02:01
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; //errorsystem("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 不能被继承。这就满足了我们设计要求。