如何在 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