c – 析构函数和解除分配的函数有什么区别?
发布时间:2020-12-16 10:04:31 所属栏目:百科 来源:网络整理
导读:这段代码中的析构函数和DeAllocate函数有什么区别? 我不明白他们对我来说看起来是一回事.他们做同样的事情,为什么你需要像DeAllocate这样的功能?析构函数具有自动调用的优点,但DeAllocate不会. #include iostreamusing namespace std;const int SIZE=5;cla
这段代码中的析构函数和DeAllocate函数有什么区别?
我不明白他们对我来说看起来是一回事.他们做同样的事情,为什么你需要像DeAllocate这样的功能?析构函数具有自动调用的优点,但DeAllocate不会. #include <iostream> using namespace std; const int SIZE=5; class ARRAY_CLASS { public: ARRAY_CLASS();//default constructor ~ARRAY_CLASS(); //destructor void Add(int); //mutator void Print(); //accessor int * Get_Address(); //accessor void DeAllocate(); //mutator private: int *A; int count; }; ARRAY_CLASS::ARRAY_CLASS() { cout<<"Default constructor has been calledn"; A = new int[SIZE]; count = 0; } ARRAY_CLASS::~ARRAY_CLASS() { cout<<"The Destructor has been Called!n"; delete [ ] A; A=0; count = 0; } void ARRAY_CLASS::Add(int item) { if (count<SIZE) A[count++]=item; else cout<<"Array Fulln"; } void ARRAY_CLASS::Print() { for(int i=0; i<count; i++) cout<<"A[i] = "<<A[i]<<endl; } int * ARRAY_CLASS::Get_Address() { return A; } void ARRAY_CLASS::DeAllocate() { delete [ ] A; A = 0; count = 0; } int main() { ARRAY_CLASS B; B.Add(1); B.Add(2); B.Add(3); B.Add(4); B.Add(5); B.Print(); ARRAY_CLASS A = B; cout<<"A holds address location = "<<A.Get_Address() <<" and B holds address location "<<B.Get_Address()<<endl; B.DeAllocate(); A.Print(); return 0; } 解决方法
人们确实可以重写析构函数:
ARRAY_CLASS::~ARRAY_CLASS() { cout<<"The Destructor has been Called!n"; DeAllocate(); } 不同之处在于: >在销毁时调用析构函数(当离开创建对象的作用域时,或者为freestore对象删除对象时,自动为本地对象调用).对象被销毁后,该对象不再存在.>当你调用DeAllocate();释放数组的内存并更改对象的状态,但其所有成员和ARRAY_CLASS对象本身仍然存在. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |