简体   繁体   English

C++ 中的 inheritance 方法重载

[英]Methods overloading while inheritance in C++

I have a legacy code:我有一个遗留代码:

struct Iface1
{
  virtual ~Iface1() {}
  virtual void foo(const int arg1) const = 0;
};

struct Iface2
{
  virtual ~Iface2() {}
  virtual void foo(const int arg1, const int arg2) const = 0;
};

/// Composite interface
struct Iface12 : Iface1, Iface2
{
};

I need to create a decorator for composite interface.我需要为复合接口创建一个装饰器。 The following code even is not compiled since it is "ambiguous" for G++ and MSVC to deduce which type of foo() is called.下面的代码甚至没有被编译,因为它对于 G++ 和 MSVC 来推断调用了哪种类型的 foo() 是“不明确的”。 Could please anyone point me out how to make the code below compile and work?谁能指出我如何使下面的代码编译和工作? (unfortunately I have no time for refactoring). (不幸的是我没有时间重构)。

And I even do not understand why the compiler cannot deduce what function to call since all function signatures are explicit.而且我什至不明白为什么编译器不能推断出 function 调用什么,因为所有 function 签名都是显式的。 Thanks.谢谢。

struct IfaceDecorator : Iface12
{
  IfaceDecorator(Iface12& iface) : impl(iface) {}

  virtual void foo(const int arg1) const
  {
    impl.foo(arg1);
  }

 virtual void foo(const int arg1, const int arg2) const
 {
   impl.foo(arg1, arg2);
 }

private:
  Iface12& impl;
};

You need explicitly import foo into the Iface12 class, so you'll get two overloaded functions Iface12::foo .您需要将foo显式导入Iface12 class,因此您将获得两个重载函数Iface12::foo

struct Iface12 : Iface1, Iface2
{
  using Iface1::foo;
  using Iface2::foo;
};

The member functions with the same name overload each other only when they are declared in the same class, if you want to overload an inherited function you need to import the name in the current class via using ParentClass::functionName .同名的成员函数只有在同一个 class 中声明时才会相互重载,如果要重载继承的 function,则需要在当前 class 中using ParentClass::functionName导入名称I think this is principle of least surprise - your member function will not be overloaded unless you ask for it.我认为这是最不意外的原则——除非您要求,否则您的成员 function 不会超载。

If the problem is in the message to impl, you can fix it with:如果问题出在要 impl 的消息中,您可以使用以下方法修复它:

impl.Iface1::foo( arg1 );
// ...
impl.Iface2::foo( arg1, arg2 );

... and so on. ... 等等。

EDITED: I've tested it and the ambiguity is over.已编辑:我已经对其进行了测试,并且歧义已经结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM