gpt4 book ai didi

c++方法可见性继承通过g++中的不同命名空间

转载 作者:行者123 更新时间:2023-11-30 04:03:57 26 4
gpt4 key购买 nike

关于 C++ 中方法可见性的一个小问题。说这段代码:

namespace A
{
class AA
{
public :
AA() {}

void foo1(int a) {} //will be overloaded in B::BB
void foo2(int a) {} //will be overloaded in B::BB
void foo3(int a) {} //won't be overloaded
};
}

using namespace A;

namespace B
{
class BB : public A::AA // ( A:: facultative but it's to test without the using namespace )
{
public:
BB() : AA() {}

void foo1(int b, int d) { AA::foo1(b); } //works
void bar3(int b, int d) { foo3(b); } //works

void foo2(int b, int d) { foo2(b); }
//doesn't work, "error : B::BB::foo2(int) not declared"
};
}

这有点像……对我来说很奇怪:为什么编译器在 B::BB 中搜索 foo2 而它正确地找到了 foo3 ?我的意思是,我知道这是因为我重载了 foo2 而不是 foo3 但为什么会有这样的行为?标准中是否有关于这种情况的内容,或者它是 g++ 中的不当行为/错误? (注意:我在 gnu90、gnu99 和 c++11 上有错误)

最佳答案

类 BB 中表面上的重载实际上并非如此:它们隐藏类 AA 中同名的成员函数。

这与在内部作用域中重新定义名称的想法相同:它在某些外部作用域中隐藏相同的名称,因此无论外部作用域多么有意义,都不会被考虑。

您可以限定调用,例如

void foo2(int b, int d) { AA::foo2(b); }

或将 AA 函数作为可见重载引入

using AA::foo2;

关于c++方法可见性继承通过g++中的不同命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996465/

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