gpt4 book ai didi

c++ - 虚函数上下文中的支配是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:24 26 4
gpt4 key购买 nike

代码示例:

考虑以下菱形层次结构:

struct A
{
virtual void f(){}
void g(){}
};
struct B : virtual A
{
virtual void f() override{}
void g(){}
};
struct C : virtual A
{
};
struct D: B, C
{
};

int main()
{
D d;
d.f(); //B::f is called
d.g(); //B::g is called
}

我所理解的:

就非虚函数g而言,一切都很清楚:名称B::g隐藏了A::g,即使名称 A::g 可以在不通过 C 隐藏的情况下访问。没有歧义。 B::g 被调用。 The standard在 10.2 p.10 中明确证实了这一点:

[ Note: When virtual base classes are used, a hidden declaration can be reached along a path through the subobject lattice that does not pass through the hiding declaration. This is not an ambiguity. The identical use with non-virtual base classes is an ambiguity; in that case there is no unique instance of the name that hides all the others. — end note ] [Example:

此外,this answer对相关问题提供了对该问题的详尽解释。

问题:

我不明白的是上面提到的引用是如何与虚函数f相关的。 f 没有隐藏名字,是吗?只涉及重写,10.3 p.2 是这样写的:

A virtual member function C::vf of a class object S is a final overrider unless the most derived class (1.8) of which S is a base class subobject (if any) declares or inherits another member function that overrides vf. In a derived class, if a virtual member function of a base class subobject has more than one final overrider the program is ill-formed.

现在,在我看来,虚函数 f 完全符合 具有最终覆盖程序的定义,程序应该是病式的。但事实并非如此。或者是吗? MSVC 编译它很好,有以下警告:

warning C4250: 'D' : inherits 'B::B::f' via dominance

老实说,我以前从来没有遇到过“支配”这个词。当我在标准中搜索它时,它在索引中出现了一次,并让我找到了我的第一句话来自的章节。而且,正如我已经提到的,这句话似乎只涉及名称隐藏而不是虚函数覆盖。

问题:

  • f 在 D 中是否有不止一个最终覆盖?
  • 支配规则是否适用于这种情况?它如何遵循标准?

最佳答案

我将再次引用 [10.3]/2:

A virtual member function C::vf of a class object S is a final overrider unless the most derived class (1.8) of which S is a base class subobject (if any) declares or inherits another member function that overrides vf. In a derived class, if a virtual member function of a base class subobject has more than one final overrider the program is ill-formed.

因此在您的示例中,A::f 不是最终覆盖程序,因为 D(最派生类)继承了 B::f 覆盖它。 B::f 是最终覆盖程序,因此被调用。

如果有多个最终覆盖程序(例如,如果 C 也覆盖 f),程序将是非良构的,但只有一个,所以一切很好。

Clang 和 GCC 编译此 without a single warning .

回答您的问题,the documentation on C4250 warning准确描述了您的情况,而支配显然是指 [10.3]/2 中描述的行为。

关于c++ - 虚函数上下文中的支配是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26854490/

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