覆盖扩展现有函数的方法

arm*_*dle 1 c++ inheritance overriding

我有一个班级Child,继承自班级Parent.Class Parent有一个虚拟保护方法_parentClassMethod(int a, int b).该方法用于类的方法Child:

void Child::_childClassMethod(int c, int d)
{
//some code
_parentClassMethod(int a, int b);
//some more code
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:在_parentClassMethod,有一个函数调用,我需要在从Child类调用时做不同的事情.我消隐了,但有没有更好的办法做到这一点以外重新定义了整个_parentClassMethodChild班?

parentClassMethod的定义:

void Parent::_parentClassMethod(int a, int b){
//lots of other code
setSomethingFunction(val1, val2, val3);/*this function cannot be made virtual since it               writes to the eeprom of a device*/
//lot more code
}
Run Code Online (Sandbox Code Playgroud)

小智 6

如果要从子方法调用父方法,可以执行以下操作:

void Child::themethod(int c, int d)
{
    Parent::themethod(c,d);
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Ola*_*che 5

在父类中定义一个虚函数,并在子类中重写它(感谢@ k-ballo).

class base {
public:
    virtual void f() { /* do parent thing */ }
    void _parentClassMethod(int a, int b) {
        // something
        f();
        // more stuff
    }
};

class derived : public base {
public:
    virtual void f() { /* do child thing */ }
};
Run Code Online (Sandbox Code Playgroud)