具有相同纯虚函数的两个基类
Two base classes with the same pure virtual function
我有一个class A继承自class B。所以class A的接口包含class B的一些纯虚函数和一些函数class A 的。现在我需要为 class A 进行单元测试,所以想要为 class A 提供一些我可以模拟的接口。
所以现在我想知道给定的代码在 C++14 中是否正确,它是否会导致 UB:
class Base1 {
public:
virtual void func() = 0;
};
class Base2 {
public:
virtual void func() = 0;
};
class Derived : public Base1, public Base2 {
public:
void func() override { }
};
int main() {
Derived d;
d.func();
return 0;
}
是的,此代码是 well-formed,void func()
覆盖了 A::func()
和 B::func()
。来自 C++14 标准:
[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
.
我有一个class A继承自class B。所以class A的接口包含class B的一些纯虚函数和一些函数class A 的。现在我需要为 class A 进行单元测试,所以想要为 class A 提供一些我可以模拟的接口。 所以现在我想知道给定的代码在 C++14 中是否正确,它是否会导致 UB:
class Base1 {
public:
virtual void func() = 0;
};
class Base2 {
public:
virtual void func() = 0;
};
class Derived : public Base1, public Base2 {
public:
void func() override { }
};
int main() {
Derived d;
d.func();
return 0;
}
是的,此代码是 well-formed,void func()
覆盖了 A::func()
和 B::func()
。来自 C++14 标准:
[class.virtual]
- If a virtual member function
vf
is declared in aclass Base
and in aclass Derived
, 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
.