问题描述
我正在检查一些代码,计划对其进行调整以适合我的研究.因此头文件看起来像这样
I am going through some code,plan to adapt it for my research.So header file looks like this
#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文件中使用虚拟析构函数.从此中,我们可以了解到,当您可以删除虚拟实例的实例时,虚拟析构函数非常有用.通过指向基类的指针派生的类.但是我认为这段代码不是这种情况.有人可以解释所有这些吗?
So I do not understand why virtual destructor was used in the .h file. From this we can learn that virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class.But I think this is not case with this code.Can someone explain all this?
推荐答案
将析构函数设为虚拟的原因是,您计划将该类进行多态继承和使用.如果我们有
The reason you would make a destructor virtual is that you plan for that class to be inherited and used polymorphicly. If we had
class Foo {};
class Bar : public Foo {};
Foo * f = new Bar();
delete f; // f's destructor is called here
将调用Foo
的析构函数,并且对象的Bar
部分的任何成员都不会被销毁.如果Foo
具有虚拟析构函数,则将执行vtable查找,而将调用Bar
析构函数,而不是正确地破坏对象.
The destructor for Foo
would be called and no members of the Bar
part of the object would be destroyed. If Foo
had a virtual destructor then a vtable lookup would happen the the Bar
destructor would be called instead correctly destroying the object.
这篇关于为什么要使用虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!