先声明这是一个纯学术问题,因为我想做的事情可以通过多层继承更好的完成。
也就是说,我想知道是否可以在不编写包装器或添加任何继承层的情况下使用现有函数覆盖虚函数。代码:
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(); };
不,没有。
关于c++ - 用现有函数覆盖虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555653/