gpt4 book ai didi

c++ - 具有相同纯虚函数的两个基类

转载 作者:太空狗 更新时间:2023-10-29 21:11:56 25 4
gpt4 key购买 nike

我有一个继承自B类的A类。所以A类的接口(interface)包含B类的一些纯虚函数和A类的一些函数。现在我需要对A类进行单元测试,所以想要我可以模拟的 A 类的一些接口(interface)。所以现在我想知道给定的代码在 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;
}

最佳答案

是的,这段代码格式正确,void func() 覆盖了 A::func()B::func()。来自 C++14 标准:

[class.virtual]

  1. 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.

关于c++ - 具有相同纯虚函数的两个基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48827297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com