【问题标题】:is it possible to hide an overloaded method while using private inheritence in c++在c ++中使用私有继承时是否可以隐藏重载方法
【发布时间】:2011-11-26 20:17:17
【问题描述】:
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)

【问题讨论】:

  • 请格式化您的代码,我们是人类,而不是编译器
  • 你想让cout&lt;&lt;b.fn(2)&lt;&lt;endl;成为编译器错误吗?

标签: c++ inheritance private-inheritance


【解决方案1】:

AFAIK 不,您不能从命名空间中“隐藏”名称。这与 names 相关,因此包括所有可能的同名重载。

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

这种现象导致了图书馆作者应该始终注意的鲜为人知的ADL Pitfall


PS. 在示例代码中,您当然可以直接删除/*using*/ Foo::fn; 行...但我想这不是您的实际代码...。

【讨论】:

    【解决方案2】:

    只需创建基类privateprotected(使用class时默认为private,目前还可以)并且不要使用,而是覆盖派生类中的函数

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

    这只会让 int fn() 在 Bar 和 not int fn(int) 中可见。当然编译器会大声喊,那个fn不是虚函数,你还是重写它,但只要它只调用基类中的那个,都一样。

    【讨论】:

    • 这不会覆盖方法int fn(),而是通过在封闭的命名空间中声明一个新标识符来隐藏它。我不认为it is all the same: 使用虚拟,类布局可能会有所不同,;将应用不同的优化,并且子类化时类的语义将不同。我同意,在您的样本中,观察到的行为(性能除外)是相同的。这是 OP +1 的一个很好的解决方法
    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多