为什么虚拟析构函数?

KBa*_*uin 1 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_ */
Run Code Online (Sandbox Code Playgroud)

后者在主代码中

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

SpectralClustering::SpectralClustering(Eigen::MatrixXd& data, int numDims):
    mNumDims(numDims),
    mNumClusters(0)
Run Code Online (Sandbox Code Playgroud)

所以我不明白为什么在.h文件中使用虚拟析构函数.从这个我们可以得知,虚析构函数是有用时,你可以通过指针删除派生类的实例,立足class.But我想,这是不是跟这个code.Can有人区分解释这一切?

Nat*_*ica 7

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

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

Foo * f = new Bar();
delete f; // f's destructor is called here
Run Code Online (Sandbox Code Playgroud)

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