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(); };