在本教程中,我们将讨论一个程序,以了解如何限制C ++中对象的动态分配。
为此,我们将使新的运算符函数保持私有状态,以便无法动态使用它创建对象。
#include <iostream> using namespace std; class Test{ //将新运算符设为私有 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