运行基类函数然后继承类函数

时间:2012-05-01 20:07:10

标签: c++ oop

  

可能重复:
  How to force child same virtual function call its parent virtual function first

编辑人们完全忽略了这一点:我得到的是,如果有很多类继承Base,我不想为每一个都调用Base::myFunction()


我不确定如何说出这个问题,但我希望从代码中可以看出这一点(这可能实际上并没有编译,我很快就写了):

class Base
{
    bool flag = false;

    void myFunction ()
    {
        flag = true;

        // here run the inherited class's myFunction()
    }
};

class A : public Base
{
    void myFunction ()
    {
        // do some clever stuff without having to set the flags here.
    }
};

int main ()
{
    A myClass;
    myClass.myFunction(); // set the flags and then run the clever stuff
    std::cout << myClass.flag << endl; // should print true
    return 0;
}

4 个答案:

答案 0 :(得分:4)

首先 - 如果您将使用指针,请使用虚拟函数。 然后你只需要在派生类实现中调用基类myFunction。 见例:

class Base
{
    bool flag = false;

    virtual void myFunction ()
    {
        flag = true;
    }
};

class A : public Base
{
    virtual void myFunction ()
    {
        Base::myFunction();  // call base class implementation first
        // do some clever stuff without having to set the flags here.
    }
};

int main ()
{
    A myClass;

    myClass.myFunction(); // set the flags and then run the clever stuff

    std::cout << myClass.flag << endl; // should print true

    return 0;
}

如果您不喜欢在所有派生类中调用基类函数。您可以为“聪明”计算添加特殊虚函数,并在所有派生类中单独实现。 例如:

class Base
{
    bool flag = false;

    virtual void cleverCalc() = 0;
    virtual void myFunction ()
    {
        flag = true;
        cleverCalc();
    }
};

class A : public Base
{
    virtual void cleverCalc()
    {
        // do some clever stuff without having to set the flags here.
    }
};

答案 1 :(得分:3)

class A : public Base
{
    void myFunction ()
    {
        Base::myFunction();    // <-------------------------------
        // do some clever stuff without having to set the flags here.
    }
};

答案 2 :(得分:2)

您使用空实现创建另一个函数(将在子类中重写),并在myFunction中调用它。像这样:

class Base
{
    bool flag = false;

    void myFunction ()
    {
        flag = true;

        // here run the inherited class's myFunction()
        myDerivedFunction();
    }

    virtual void myDerivedFunction()
    {
        // this should be implemented by subclasses.
    }
};

class A : public Base
{
    void myDerivedFunction ()
    {
        // do some clever stuff without having to set the flags here.
    }
};

答案 3 :(得分:0)

凭借您的继承结构,派生类中的myFunction()调用会阻止对基类中的版本的调用,因此flag永远不会设置为“true”。

相关问题