C++中子类和父类都有虚函数,类型强转时调用虚函数执行状况分析
test.cpp
#include <iostream>
using namespace std;
class Father
{
public:
virtual void call()
{
cout << "father out" << endl;
}
};
class Son : public Father
{
public:
virtual void call()
{
cout << "son out" << endl;
}
};
int main()
{
float a;
Father *father;
Father father1;
Son son;
Son *son1;
son.call();
father = (Father *)&son;
father->call();
father1.call();
son1 = (Son *)&father1;
son1->call();
cin >> a;//目的是阻塞窗口,让其不关闭,方便观察结果
return 0;
}
执行结果: