如何覆盖多重继承中具有相同名称的基 类' 虚函数?
How to override base classes' virtual functions that have identical names in multiple inheritance?
假设我有两个基础 classes B1
和 B2
,以及一个从 B1 和 B2 派生的 class D
,如下所示:
class B1 {
public:
// ...
virtual void foo() final { cout << "Hello, B1\n"; }
};
class B2 {
public:
// ...
virtual void foo() { cout << "Good riddance, B2!\n"; }
};
class D :public B1, public B2 {
// ...
};
在设计classD
时,我想覆盖B2中的成员函数foo()
;但是,B1 中的 foo()
被标记为 final
并阻止我覆盖 B2 中的 foo()
。从 B2 覆盖 foo()
的最佳方法是什么?
我认为按照您在问题中所展示的方式,您想要做的事情是不可能的。来自 N3337,§10.3/2 [class.virtual]
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 overrides Base::vf
. ...
D::foo
匹配 B1::foo
和 B2::foo
的所有条件,因此它会覆盖 和 。由于 B1::foo
是 final
,代码格式错误。
一种解决方法是引入额外的继承级别。定义一个 class,比如 D2
,它派生自 B2
并覆盖 B2::foo
。然后 D
可以派生自 B1
和 D2
。
class D2 : public B2{
public:
virtual void foo() override { cout << __PRETTY_FUNCTION__ << '\n'; }
};
class D :public B1, public D2
{};
D d;
// d.foo(); // error - ambiguous
D2& d2 = d;
d2.foo(); // calls D2::foo
B2& b2 = d;
b2.foo(); // calls D2::foo
B1& b1 = d;
b1.foo(); // calls B1::foo
假设我有两个基础 classes B1
和 B2
,以及一个从 B1 和 B2 派生的 class D
,如下所示:
class B1 {
public:
// ...
virtual void foo() final { cout << "Hello, B1\n"; }
};
class B2 {
public:
// ...
virtual void foo() { cout << "Good riddance, B2!\n"; }
};
class D :public B1, public B2 {
// ...
};
在设计classD
时,我想覆盖B2中的成员函数foo()
;但是,B1 中的 foo()
被标记为 final
并阻止我覆盖 B2 中的 foo()
。从 B2 覆盖 foo()
的最佳方法是什么?
我认为按照您在问题中所展示的方式,您想要做的事情是不可能的。来自 N3337,§10.3/2 [class.virtual]
If a virtual member function
vf
is declared in a classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) asBase::vf
is declared, thenDerived::vf
is also virtual (whether or not it is so declared) and it overridesBase::vf
. ...
D::foo
匹配 B1::foo
和 B2::foo
的所有条件,因此它会覆盖 和 。由于 B1::foo
是 final
,代码格式错误。
一种解决方法是引入额外的继承级别。定义一个 class,比如 D2
,它派生自 B2
并覆盖 B2::foo
。然后 D
可以派生自 B1
和 D2
。
class D2 : public B2{
public:
virtual void foo() override { cout << __PRETTY_FUNCTION__ << '\n'; }
};
class D :public B1, public D2
{};
D d;
// d.foo(); // error - ambiguous
D2& d2 = d;
d2.foo(); // calls D2::foo
B2& b2 = d;
b2.foo(); // calls D2::foo
B1& b1 = d;
b1.foo(); // calls B1::foo