C++编程语言允许自动(或堆栈分配)和动态分配的对象。在Java&C#中,所有对象都必须使用new动态分配。
null
由于运行时效率的原因,C++支持堆栈分配对象。基于C++的编译器隐式地管理基于堆栈的对象。当它们超出范围时会被销毁,必须使用delete操作符手动释放动态分配的对象,否则会发生内存泄漏。C++不支持诸如java和C语言等语言使用的自动垃圾收集方法。
如何从C++中的类“测试”中获得以下行为?
Test* t = new Test; // should produce compile time errorTest t; // OK
这样做的目的是保持新操作符函数的私有性,以便不能调用new。请参阅以下程序。无法使用new创建“Test”类的对象,因为new operator函数在“Test”中是私有的。如果我们取消main()第二行的注释,程序将产生编译时错误。
CPP
// CPP Program to restrict dynamic // allocation of objects in C++ #include <iostream> using namespace std; // Objects of Test can not be // dynamically allocated class Test { // new operator function is private void * operator new ( size_t size); int x; public : Test() { x = 9; cout << "Constructor is called" ; } void display() { cout << "x = " << x << "" ; } ~Test() { cout << "Destructor is executed" ; } }; // Driver Code int main() { // Test* obj=new Test(); -> Uncommenting this line would // cause a compile time error. Test t; // Ok, object is allocated at compile time t.display(); // object goes out of scope, destructor will be called return 0; } |
输出
Constructor is calledx = 9Destructor is executed
此外,如果我们可以在C++中动态地为对象分配内存,这是一个通用的查询。
是的,我们也可以动态分配对象。
- 每当创建一个新对象、构造函数时,就会调用一个类的成员函数。
- 每当对象超出范围时,就会调用析构函数类成员函数。
本文由 普拉瓦西会面 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END