天天看點

對象建立問題:heapOnly,stackOnly代碼(C++代碼)

class   HeapOnly 

public: 

 HeapOnly()

 {   

  cout<<"constructor. "<<endl;   

 } 

 void destroy()

 {   

  delete this;   

 } 

private: 

 ~HeapOnly(){}   

};   int main() 

 HeapOnly   *p = new HeapOnly; 

 p->destroy(); 

 HeapOnly h; 

 h.Output();    return 0; 

}  

#include   <iostream> 

using   namespace   std;   class StackOnly 

public: 

 StackOnly()   

 {   

  cout<<"constructor." <<endl;   

 } 

 ~StackOnly()   

 {   

  cout<<"destructor." <<endl;   

 } 

private: 

 void *operator new (size_t); 

};   int main() 

 StackOnly s;                        //okay 

 StackOnly *p = new StackOnly;       //wrong 

 return   0; 

}