如何限制C ++中对象的动态分配?
在本教程中,我们将讨论一个程序,以了解如何限制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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短