c++ - 为什么是虚拟析构函数?

标签 c++ inheritance virtual-destructor

我正在检查一些代码,计划根据我的研究对其进行调整。所以头文件看起来像这样

#ifndef SPECTRALCLUSTERING_H_
#define SPECTRALCLUSTERING_H_

#include <vector>
#include <eigen3/Eigen/Core>

class SpectralClustering {
public:
    SpectralClustering(Eigen::MatrixXd& data, int numDims);
    virtual ~SpectralClustering();

    std::vector<std::vector<int> > clusterRotate();
    std::vector<std::vector<int> > clusterKmeans(int numClusters);
    int getNumClusters();

protected:
    int mNumDims;
    Eigen::MatrixXd mEigenVectors;
    int mNumClusters;
};

#endif /* SPECTRALCLUSTERING_H_ */

主要代码在后面

#include "SpectralClustering.h"
#include <eigen3/Eigen/QR>

SpectralClustering::SpectralClustering(Eigen::MatrixXd& data, int numDims):
    mNumDims(numDims),
    mNumClusters(0)

所以我不明白为什么在.h文件中使用虚拟析构函数。来自 this我们可以了解到,当您可以通过指向基类的指针删除派生类的实例时,虚拟析构函数很有用。但我认为这段代码不是这种情况。有人可以解释这一切吗?

最佳答案

将析构函数设为虚拟的原因是您计划继承该类并以多态方式使用它。如果我们有

class Foo {};
class Bar : public Foo {};

Foo * f = new Bar();
delete f; // f's destructor is called here

将调用 Foo 的析构函数,并且不会销毁对象的 Bar 部分的任何成员。如果 Foo 有一个虚拟析构函数,那么将调用 vtable 查找 Bar 析构函数,而不是正确地销毁对象。

关于c++ - 为什么是虚拟析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32094700/

相关文章:

css - 元素动画关键帧的继承

c++ - 没有虚拟析构函数可能会发生内存泄漏?

c++ - 从类返回渲染窗口

TEXT 宏中的 C++ 字符串变量

java - 从列表转换为集合

Python 动态继承 : How to choose base class upon instance creation?

c++ - 虚拟析构函数改变 decltype 的行为

c++ - 使用 Cloaking 模式时需要虚拟析构函数吗?

c++ - 使用 cornerHarris 知道角的数量

c++ - 读取二进制文件并正确使用流迭代器