这是我编写的一段代码,用于查看向下转换期间的行为。
#include <iostream>
using namespace std;
class base {
public :
void function()
{
cout << "\nInside class Base";
}
};
class derived : public base {
public :
void function()
{
cout << "\nInside class Derived.";
}
};
int main()
{
base * b1 = new base();
base * b2 = new derived();
derived * b3 = (derived*)b1 ;
b1 -> function();
b2 -> function();
b3 -> function(); // print statement 3
static_cast<derived*>(b2) -> function();
static_cast<derived*>(b1) -> function(); // print statement 5
return 0;
}
输出如下。
Inside class Base
Inside class Base
Inside class Derived.
Inside class Derived.
Inside class Derived.
我觉得 print statement 3 和 print statement 5 应该已经显示了 "Inside class base" 。
有人可以解释一下我在这里可能缺少什么吗?