我正在检查一些代码,计划根据我的研究对其进行调整。所以头文件看起来像这样
#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/