c++ - C++ 基类的成员真的需要是虚拟的才能被派生类覆盖吗?

标签 c++ polymorphism virtual members

class A { 
    public: 
    virtual int test()=0; 
};

class B : public A { 
   public: 
   int test(){return 10;}
};


B *b = new B();
b->test(); // would return 10;

鉴于:

class A { 
    public: 
    int test(){return 0;}
};

class B : public A { 
   public: 
   int test(){return 10;}
};


B *b = new B();
b->test(); // **would return 0**;

为什么这里返回“0”?这对我来说毫无意义,因为我假设派生类 (B) 的(重载的)成员是第一位的! 这里发生了什么?

最佳答案

除了无效语法(B->test(); 应该是 b->test();),第二个也会返回 10 .

如果相反,你会这样写:

A* a = new B();
a->test();

它会返回 0 或 10,具体取决于 A::test 是否是虚拟的。

关于c++ - C++ 基类的成员真的需要是虚拟的才能被派生类覆盖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840147/

相关文章:

c++ - 从三个 3D 点计算变换矩阵

python - C++ 中的 Crypto++ :Encrypt in Python , 解密

c++ - OpenCV 3.0 无法加载神经网络

java - 静态方法和多态性

c++ - 多态性和指向数组的指针

c++ - 带有可变参数模板的奇怪的重复模板模式 (C++)

c++ - 关于纯抽象类中的静态成员函数 - 设计模式?

c++ - 对vtable的 undefined reference -C++链接错误

c++ - 是什么让虚函数这么慢? C++

c++ - 意外输出...函数绑定(bind)如何在虚拟表中发生