题目:编写C++中的两个类
要求:一个只能在栈中分配空间 一个只能在堆中分配
源代码
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class CHeapOnly
- {
- public:
- CHeapOnly()
- {
- cout << "Constructor() of CHeapOnly!" << endl;
- }
- public:
- void Destroy() const
- {
- delete this;
- }
- private:
- ~CHeapOnly()
- {
- cout << "Destructor of CHeapOnly!" << endl;
- }
- };
- class CStackOnly
- {
- public:
- CStackOnly()
- {
- cout << "Constructor of CStackOnly!" << endl;
- }
- ~CStackOnly()
- {
- cout << "Destrucotr of CStackOnly!" << endl;
- }
- private:
- void* operator new(size_t)
- {
- }
- };
- int main()
- {
- //use of CHeapOnly
- CHeapOnly* pHeap = new CHeapOnly;
- pHeap->Destroy();
- //err use of CHeapOnly
- //CHeapOnly objHeap;
- //use of CStackOnly
- CStackOnly objStack;
- //error use of CStackOnly
- //CStackOnly* pStack = new CStackOnly;
- return 0;
- }