gpt4 book ai didi

c++ - 在没有菱形继承(钻石问题)的情况下,C++ 中的函数重载如何工作?

转载 作者:行者123 更新时间:2023-11-30 01:37:02 25 4
gpt4 key购买 nike

在下面的例子中,

void f(double, double);  // at global scope

struct Grandparent {
void f(int);
void f(double, double);
};

struct Parent : public Grandparent {
void f(int); // hides all overloads of Grandparent::f
};

struct Child : public Parent {
void g() { f(2.14, 3.17); } // resolves to Parent::f
};

无论签名如何,Parent::f 的声明如何控制和隐藏所有更古老的声明,即 Parent::f(int)控制并隐藏 Grandparent::f(double, double) 的声明即使这两个成员函数具有非常不同的签名?

我是通过 https://en.wikipedia.org/wiki/Dominance_(C%2B%2B) 看到这个例子的

最佳答案

因为隐藏的是name;不涉及签名。根据name lookup的规则,

name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.

对于这种情况,当在 Parent 的范围内找到名称 f 时,名称查找将停止; Grandparent 中的名字根本不会被考虑。 (顺便说一句:名称查找后,将检查重载解析签名以选择最匹配的签名)

如果这不是您预期的行为,您可以通过using 引入名称。

struct Parent : public Grandparent {
using Grandparent::f;
void f(int);
};

struct Child : public Parent {
void g() { f(2.14, 3.17); } // refer to Grandparent::f(double, double)
};

关于c++ - 在没有菱形继承(钻石问题)的情况下,C++ 中的函数重载如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480714/

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