在c++中使用私有继承时是否可能隐藏重载方法?

is it possible to hide an overloaded method while using private inheritence in c++

本文关键字:是否 隐藏 重载 方法 继承 c++      更新时间:2023-10-16
class Foo
{
public:
    int fn()
    {
        return 1;
    }
    int fn(int i)
    {
        return i;   //2nd fn()
    }
};
class Bar:Foo
{
public :
    Foo::fn;
};
int main(int argc, char** argv)
{
    Bar b;
    cout<<b.fn(2)<<endl;
}

不可能在具体类"Bar"中隐藏fn(int)

不,您不能从名称空间中"隐藏"名称。这与名称有关,因此包含了所有可能的同名重载。

同样,没有办法unusing一个名称/命名空间。

这种现象导致了一个鲜为人知的ADL陷阱,库作者应该始终注意这个陷阱。


p。在示例代码中,当然你可以直接去掉/*using*/ Foo::fn; line…但我猜这不是你的实际代码....

只是使基类private, protected(使用class时默认为private,到目前为止,ok),不使用,但在派生类中重写函数

class Bar: private Foo
{
public:
    int fn() {return Foo::fn();}
};

这只会使int fn()在Bar和not int fn(int)中可见。当然,编译器会大声嚷嚷,fn不是虚函数,但你仍然覆盖它,但只要它只调用基类中的一个,它都是一样的。