【问题标题】:Why do I need to redeclare overloaded virtual functions?为什么我需要重新声明重载的虚函数?
【发布时间】:2021-03-09 05:37:29
【问题描述】:

我有一个带有两个重载函数f(void)f(int) 的基类。 Derived 类通过调用 f(void) 实现 f(int)Derived2 仅实现 f(void)

编译器拒绝实现Derived::f(int),因为它想调用f(int),但我没有提供任何参数,因为我想调用f(void)。为什么编译器会拒绝它?为什么添加行 virtual int f(void) = 0; 可以解决我的问题?

class Base
{
public:
  explicit Base(void) {}
  virtual ~Base(void) {}

  virtual int f(void) = 0;
  virtual int f(int i) = 0;
};

class Derived : public Base
{
public:
  // provide implementation for f(int) which uses f(void). Does not compile.
  virtual int f(int i) {puts("Derived::f(int)"); return f();}
  // code only compiles by adding the following line.
  virtual int f(void) = 0;
};

class Derived2 : public Derived
{
public:
  // overwrite only f(void). f(int) is implemented by Derived.
  virtual int f(void) {puts("Derived2::f(void)"); return 4;}
};

int main(void)
{
  Base * p = new Derived2();
  int i0 = p->f();  // outputs Derived2::f(void) and returns 4
  int i1 = p->f(1); // outputs "Derived::f(int) Derived2::f(void)" and return 4
  delete p;
  return 0;
}

【问题讨论】:

    标签: c++ polymorphism overloading virtual


    【解决方案1】:

    Derived::f 隐藏Base::fs。在Derived::f(int) 的主体中给定return f();,在Derived 的范围内找到名称f,然后name lookup 停止。 Base 中的名称将不会被找到并参与重载解析。

    名称查找如下所述检查范围,直到找到至少一个任何类型的声明,此时查找停止并且不再检查范围。

    您可以添加using Base::f;,将Base的名称引入Derived的范围内。

    class Derived : public Base
    {
    public:
      using Base::f;
    
      // provide implementation for f(int) which uses f(void).
      virtual int f(int i) {puts("Derived::f(int)"); return f();}
    };
    

    【讨论】:

    • 或者最好不要为这些函数使用相同的名称。
    • 我不知道 OP 在执行什么操作,但同时使用静态和动态多态性恕我直言不是一个好主意。但是,如果 OP 想要强硬的方式,谁会阻止他?
    • 我喜欢你的回答。也许您可以解释我的重新声明和您的“使用 Base::f”解决方案之间的区别。你的解决方案有什么优势吗?
    • @Slava Derived2类有很多,Derived是一个避免重写大量代码的适配器。因此名称是固定的。
    • @Fabian 鉴于您展示的代码,效果是相同的。我能想到的区别是如果Base中有很多重载函数f,而using Base::f;你不需要在Derived中声明每个f
    猜你喜欢
    • 2017-02-28
    • 2020-10-19
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2014-10-15
    相关资源
    最近更新 更多