以前了解析构函数必须是虚构函数,但是一直没有深究到底问什么,今天忽然好奇,做了一些测试才搞明白(猜测)。。。。
先做两个测试
using namespace std;
class father{
public:
void print(){
cout<<"this is father"<<endl;
}
};
class son :public father{
public:
void print(){
cout<<"this is son"<<endl;
}
};
int main(){
son * son1=new son();
father * father1=static_cast<father *>(son1);
father1->print();
return 0;
}
输出为:
this is father
#include<iostream>
using namespace std;
class father{
public:
virtual void print(){
cout<<"this is father"<<endl;
}
};
class son :public father{
public:
void print(){
cout<<"this is son"<<endl;
}
};
int main(){
son * son1=new son();
father * father1=static_cast<father *>(son1);
father1->print();
return 0;
}
输出为:
this is son
可以发现对于非虚函数的成员函数,调用时会执行指针类型的函数。对于virtual修饰的虚函数,调用时只会执行指针指向的实际对象的函数。猜测是由于强转之后虚函数表或者说虚表指针不发生改变,而普通成员函数用过指针类型进行调用的。
以上是子类强转为基类,将基类强转为子类也可以发现相同的结论。
这也就解释了为啥析构函数必须是虚函数,如果不是虚函数,那么如果子类强转为基类,调用的将是基类的函数,而不是子类的,就会析构不完全造成内存泄露。
Ps.结论不严谨,有错误还请指正