Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用现有函数重写虚拟函数_C++_Inheritance - Fatal编程技术网

C++ 用现有函数重写虚拟函数

C++ 用现有函数重写虚拟函数,c++,inheritance,C++,Inheritance,首先让我说这是一个纯粹的学术问题,因为我想做的事情可以通过多层继承更好地完成 也就是说,我想知道是否有可能在不编写包装器或添加任何继承层的情况下用现有函数重写虚拟函数。代码: int myfunc2() { return 2; } class Parent { public: virtual int myfunc() { return 0; } }; class Child1 : public Parent { public: int myfunc() override { re

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

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

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

这是可能的,还是类似的

Context:我有一堆子类,其中一些子类具有与
myfunc
相同的定义,而有些子类则没有。更好的解决方案是创建一个中间子类来定义公共的
myfunc
,并让相关的子类从中继承

不,没有

不,没有。有个问题

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

有一个问题

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

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