用现有函数覆盖虚拟函数

Override virtual function with existing function

本文关键字:函数 覆盖 虚拟      更新时间:2023-10-16

首先让我说这是一个纯粹的学术问题,因为我想做的事情可以通过多层继承更好地完成。

也就是说,我想知道是否可以在不编写包装器或添加任何继承层的情况下用现有函数覆盖虚拟函数。 法典:

int myfunc2() { return 2; }
class Parent {
 public:
  virtual int myfunc() { return 0; }
};
class Child1 : public Parent {
 public:
  int myfunc() override { return 1; }
};
class Child2 : public Parent {
 public:
  // There a way to do this?
  // int myfunc() = myfunc2;
  // instead of this?
  int myfunc() { return myfunc2(); };
};
int main() {
  Child2 baz;
  return baz.myfunc();
}

我想通过简单地将声明"转发"到现有的myfunc2声明来覆盖Child2定义中的myfunc

这可能吗,或者类似的东西,可能吗?

上下文:我有一堆子类,其中一些对myfunc的定义相同,其中一些没有。 更好的解决方案是创建一个定义公共myfunc的中间子类,并改为让相关的子类继承该子类。

// There a way to do this?
// int myfunc() = myfunc2;
// instead of this?
int myfunc() { return myfunc2(); };

不,没有。

有一个问题。

非静态成员函数接受另一个隐式参数:指向对象本身的指针。虽然独立函数没有这样的参数,例如,您不能在独立函数的定义中使用关键字this或成员访问语法。