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 ++ 场景,我的问题是:
提前致谢!
答案 0 :(得分:1)
- 我可以将此方案称为多态吗?
醇>
没有
- 如果是,那么我可以将其称为静态/编译时多态吗?
醇>
没有。见下文。
- 如果不是,那么我是否应该假设这是一个不正确的实现并且必须使用虚拟?
醇>
是的,使用virtual void f();
应修复您的样本。您可以使用静态多态性virtual
来解决这个问题:
template<typename Derived>
class A{
public:
void f(){
static_cast<Derived*>(this)->fImpl();
}
void fImpl() {
cout<<"I m called from A"<<endl;
}
};
class B : public A<B> {
public:
void fImpl(){
cout<<"I m called from B"<<endl;
}
};