让B类扩展A类并覆盖它的函数我们可以确定当发送(B *)的实例好像它是类型(A *)时,我们在类B中创建的覆盖将被调用吗?
答案 0 :(得分:4)
只要将A
上的方法定义为虚拟,就会出现指针和引用的情况。例如
class A {
virtual void Method() {
cout << "A::Method" << endl;
}
};
class B {
// "virtual" is optional on the derived method although some
// developers add it for clarity
virtual void Method() {
cout << "B::Method" << endl;
}
};
void Example1(A* param) {
param->Method();
}
void Example2(A& param) {
param.Method();
}
void main() {
B b;
Example1(&b); // Prints B::Method
Example2(b); // Prints B::Method
}
答案 1 :(得分:3)
是的,如果声明了virtual
函数 - 请参阅http://www.parashift.com/c++-faq-lite/virtual-functions.html
答案 2 :(得分:2)
仅当A中的函数声明为virtual
时。声明virtual
时,即使将其转换为父类,也会调用任何重写的子函数。