用现有函数覆盖虚拟函数
Override virtual function with existing function
首先让我说这是一个纯粹的学术问题,因为我想做的事情可以通过多层继承更好地完成。
也就是说,我想知道是否可以在不编写包装器或添加任何继承层的情况下用现有函数覆盖虚拟函数。 法典:
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
或成员访问语法。
相关文章:
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 如何使用用户定义的函数覆盖 C lib 函数,如 _sbrk?
- 函数覆盖有哪些用例?
- 在子类函数覆盖中省略具有默认值的参数
- C++ 成员变量被非成员函数覆盖
- 用现有函数覆盖虚拟函数
- 函数覆盖是否由编译器自动完成
- 结构被库函数覆盖
- 当在Python中定义__str__时,如何将C 的标准全局函数覆盖
- C++类是否解决函数覆盖问题
- 用私有基函数覆盖公共虚拟函数
- 优先级队列中复制构造函数覆盖的值
- 虚拟函数覆盖预期错误
- C++中的函数覆盖无需"虚拟"即可工作
- C++虚拟函数覆盖
- 如何用非虚拟函数覆盖虚拟函数
- 基成员函数的所有重载是否可以被单个模板化成员函数覆盖和转发到
- C++继承函数覆盖
- 纯虚函数覆盖虚函数
- 引用项目的Qt-main()函数覆盖实际项目的main()