这么多年后,我陷入了一种奇怪的困惑。我知道运行时多态性问题、虚函数和许多这些东西,但不能确定下面的代码示例:
class A{
public:
void f(){
cout<<"I m called from A"<<endl;
}
};
class B : public A{
public:
void f(){
cout<<"I m called from B"<<endl;
}
};
int main(void){
B* b1 = new B();
A* a1 = b1; //Object reference of class B is assigned to a pointer of class A
b1->f(); //Output is "I m called from B"
a1->f(); //Output is "I m called from A"
return 0;
}
考虑到我的问题上面的C++场景是:
- 我可以将这种情况称为多态性吗?
- 如果是,那么我可以将其称为静态/编译时多态性吗?
- 如果不是,那么我应该假设这是一个不正确的实现并且必须使用 virtual 吗?
提前致谢!