发送类实例时是否会调用覆盖,就好像它是带有覆盖的类型一样?

时间:2011-02-02 05:59:52

标签: c++ oop class virtual

让B类扩展A类并覆盖它的函数我们可以确定当发送(B *)的实例好像它是类型(A *)时,我们在类B中创建的覆盖将被调用吗?

3 个答案:

答案 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时,即使将其转换为父类,也会调用任何重写的子函数。