如何在 C++ 中限制物件的動態分配?


在本教程中,我們將討論一個程式,以瞭解如何在 C++ 中限制物件的動態分配。

為此,我們將保留新的操作函式私有,以便無法使用它動態建立物件。

示例

 即時演示

#include <iostream>
using namespace std;
class Test{
   //making new operator private
   void* operator new(size_t size);
   int x;
   public:
   Test() { x = 9; cout << "Constructor is called\n"; }
   void display() { cout << "x = " << x << "\n"; }
   ~Test() { cout << "Destructor is executed\n"; }
};
int main(){
   Test t;
   t.display();
   return 0;
}

輸出

Constructor is called
x = 9
Destructor is executed

更新於:02-Mar-2020

189 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.