如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP