簡體   English   中英

C++ 中的 inheritance 方法重載

[英]Methods overloading while inheritance in C++

我有一個遺留代碼:

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
{
};

我需要為復合接口創建一個裝飾器。 下面的代碼甚至沒有被編譯,因為它對於 G++ 和 MSVC 來推斷調用了哪種類型的 foo() 是“不明確的”。 誰能指出我如何使下面的代碼編譯和工作? (不幸的是我沒有時間重構)。

而且我什至不明白為什么編譯器不能推斷出 function 調用什么,因為所有 function 簽名都是顯式的。 謝謝。

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;
};

您需要將foo顯式導入Iface12 class,因此您將獲得兩個重載函數Iface12::foo

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

同名的成員函數只有在同一個 class 中聲明時才會相互重載,如果要重載繼承的 function,則需要在當前 class 中using ParentClass::functionName導入名稱我認為這是最不意外的原則——除非您要求,否則您的成員 function 不會超載。

如果問題出在要 impl 的消息中,您可以使用以下方法修復它:

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

... 等等。

已編輯:我已經對其進行了測試,並且歧義已經結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM