0

重複の可能性:
子の同じ仮想関数を強制的にその親仮想関数を最初に呼び出す方法

編集人々は完全にポイントを逃しています:私が得ていたのは、多くのクラスが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

4 に答える 4

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.
    }
};
于 2012-05-01T20:11:09.800 に答える
3
class A : public Base
{
    void myFunction ()
    {
        Base::myFunction();    // <-------------------------------
        // do some clever stuff without having to set the flags here.
    }
};
于 2012-05-01T20:10:05.947 に答える
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.
    }
};
于 2012-05-01T20:17:58.863 に答える
0

継承構造により、派生クラスでの myFunction() 呼び出しは基本クラスでのバージョンの呼び出しを排除するため、フラグが「true」に設定されることはありません。

于 2012-05-01T20:11:40.847 に答える