以下代码打印 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/