c++ - C++ 中 3 个类的多态性

标签 c++

以下代码打印 1 2,但我希望它打印 1 1。

#include <iostream>

using namespace std;

class A {
public:
    virtual void f() { cout << "0" << endl; }
}; 

class B : public A{
public:
    void f() { cout << "1" << endl; }
};

class C : public B{
public:
    void f() { cout << "2" << endl; }
};

int main() {
    A *pa = new B();
    B *pb = new C();
    pa->f();
    pb->f();
}

在我的理解中,pa->f() 执行 B 的 f() 函数,因为 A 是虚拟的,但为什么 pb->f() 执行 C 的 f() 函数,而 B 的 f() 不是虚拟的。

此外,如果我从类 A 中删除“虚拟”,它会打印 0 1,这是有道理的,因为 A 和 B 执行它们自己的 f() 函数,因为它们不是虚拟的。如果 pb->f() 不受影响,为什么它会发生变化,因为只有 A 会发生变化?

最佳答案

but why does pb->f() execute C's f() function when B's f() is not virtual.

因为pb的动态类型是C,而C::f确实是virtual。当你声明

virtual void f();

在基类中,层次结构中派生类的所有其他 void f() 也是虚拟的,根据 §10.3/2:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref- qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides112 Base::vf.

(强调我的)

事实上:

class A {
public:
    virtual void f() { cout << "0" << endl; }
}; 

class B : public A{
public:
    virtual void f() { cout << "1" << endl; }
};

class C : public B{
public:
    virtual void f() { cout << "2" << endl; }
};

等同于您的代码。碰巧 C++ 标准允许在这些情况下省略 virtual

关于c++ - C++ 中 3 个类的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22936579/

相关文章:

c++ - Qt 无法给 QLabel 赋值

c++ - 在 Clang 中判断访问的 CXXRecordDecl 是类、结构还是 union

c++ - 如何在我指向的andress上动态分配内存?

c++ - 如何在LLVM中删除无条件分支?

c++ - 在 map 中就地构建不可 move 的对象

c++ - 为什么存储整数的内存块的值会反复变化?

c++ - 从 VBA Excel 调用 SAP 客户端

c++ - 引用 Doxygen 类或命名空间列表 from\mainpage

c++ - 运算符需要零个或一个参数

c++ - 如何确定 C++ 中每个核心的 CPU 消耗