关于虚拟析构函数,我有三个理论问题:
假设我有一个基类Base
- 两个派生类Derivative_1
和Derivative_2
,类Stand_Alone
和类Project
。
班级Stand_Alone
在Base
和Project
中都是私人会员。
class Project
具有私有成员:Derivative_1
的对象,Derivative_2
个对象的动态数组和Stand_Alone
个对象。
例如,假设在main中只创建了一个Project
对象。
Project
正确的析构函数 - 取消分配对象的所有动态内存吗?Base
的析构函数声明为virtual
?Derivative_1
和Derivative_2
的析构函数不应声明为virtual
,对吧?感谢。
#ifndef PROJECT_H
#define PROJECT_H
#include "Stand_Alone.h"
#include "Derivative_1.h"
#include "Derivative_2.h"
class Project
{
public:
Project();
~Project()
{
delete [] support;
support = NULL;
}
protected:
private:
Stand_Alone member;
Derivative_1 head;
Derivative_2 *support;
};
#endif // PROJECT_H
答案 0 :(得分:1)
- 是
醇>Project
正确的析构函数 - 取消分配对象的所有动态内存吗?
是的,尽管有更安全的方法可以做到这一点。您可以声明Derivative_2
个对象的向量,而不是自己操作内存。这样你根本不需要声明析构函数,因为编译器提供的默认析构函数可以很好地完成工作。
- 是否应将
醇>Base
的析构函数声明为virtual
?
是的,这是确保在其子类的对象被销毁时将被调用的唯一方法。