0
class A
{
   protected:
    void func1() //DO I need to call this virtual?
};

class B
{
   protected:
    void func1() //and this one as well?
};

class Derived: public A, public B
{
    public:

    //here define func1 where in the code there is
    //if(statement) {B::func1()} else {A::func1()}
};

func1 をどのようにオーバーライドしますか? それとも定義できますか

class Derived: public A, public B
{
    public:

    void func1()
};

仮想またはオーバーライドなしで?アクセシビリティがわかりません。ありがとうございました。

4

1 に答える 1

4

レナード・ライ

オーバーライドするには、同じ名前で関数を宣言するだけです。コードのコメントで機能を実現するには、Derived func1() に変数を渡す必要があります。

例えば:

#include <iostream>

using namespace std;

class A
{
   protected:
    void func1()    {   cout << "class A\n";    } //DO I need to call this virtual?
};

class B
{
   protected:
    void func1()    {   cout << "class B\n";    } //and this one as well?
};

class Derived: public A, public B
{
    public:

    //here define func1 where in the code there is
    //if(statement) {B::func1()} else {A::func1()}
    void func1(bool select = true)
    {
        if (select == true)
        {
            A::func1();
        }
        else
        {
            B::func1();
        }
    }
};
int main()
{
   Derived d;
   d.func1();          //returns default value based on select being true
   d.func1(true);      //returns value based on select being set to true
   d.func1(false);     // returns value base on select being set to false
   cout << "Hello World" << endl; 

   return 0;
}

これはあなたが探していることをするはずです。可能なバージョンは2つしかないため、ブール値を使用しましたが、より多くのオプションがある場合に合わせてenumorを使用できます。int

于 2013-11-04T08:54:18.347 に答える