【问题标题】:Will overrides be called when class instance was send as if it was type with out overrides?发送类实例时是否会调用覆盖,就好像它是没有覆盖的类型一样?
【发布时间】:2011-06-19 18:24:04
【问题描述】:

拥有扩展类 A 并覆盖其功能的类 B,我们能否确定当发送 (B*) 的实例时,就像它是类型 (A*) 一样,我们在类 B 中创建的覆盖将被调用?

【问题讨论】:

    标签: c++ oop class virtual


    【解决方案1】:

    只要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
    }
    

    【讨论】:

      【解决方案2】:

      是的,如果函数声明为virtual - 请参阅http://www.parashift.com/c++-faq-lite/virtual-functions.html

      【讨论】:

        【解决方案3】:

        仅当 A 中的函数声明为 virtual 时。声明 virtual 时,即使转换为父类,也会调用任何覆盖的子函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-10-27
          • 2017-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-01
          • 1970-01-01
          相关资源
          最近更新 更多