0

インターフェイスといくつかの実装があります。しかし、ある実装では、その実装でのみ使用する特定の機能があります。

class Interface
{
    virtual void foo() = 0;
}

class D1 : public Interface
{
    void foo() {}
}

class D2 : public Interface
{
    void foo() {}
    void bar() {}
}

したがって、D2::bar() 関数は D2 にのみあり、D2 実装のみに指定されています。OOPを使用してそのようなものを書く正しい方法は何ですか?

私のクライアント コードでは、Interface* i; という呼び出しがあります。i->foo();

ただし、「i」が D2 の場合、場合によっては bar() 関数を呼び出す必要があります。

4

5 に答える 5

1

bar 関数を呼び出す必要がある場合は、bar を認識しているオブジェクトへの参照が必要です。

したがって、D2 オブジェクトを参照するか、インターフェイスに bar 関数を含める必要があります。後者の場合、D1 もそれを実装する必要がありますが、実装は空にするか、エラー値を返すことができます。

于 2012-08-31T07:52:57.097 に答える
0

インターフェイスに一般的な実装を用意する準備ができている場合は、インターフェイスに bar() の空の実装を配置します。

class Interface
{
    virtual void foo() = 0;
    virtual void bar() {}
}

class D1 : public Interface
{
    void foo() {}
}

class D2 : public Interface
{
    void foo() {}
    void bar() {}
}

Interface i* = blah; を呼び出すと、i->バー(); i が D1 の場合は何もしません。i が D2 の場合は、D2 固有の処理を行います。

于 2012-08-31T09:07:36.733 に答える
0

インターフェイスの使用を主張する場合はbar、専用のインターフェイスに移動してから、クライアントにそれを使用させる必要があります。

class FooInterface {
public:
    virtual void foo() = 0;
};

class BarInterface {
public:
    virtual void bar() = 0;
};

class D1 : public FooInterface {
public:
    void foo() {}
};

class D2 : public FooInterface,
           public BarInterface {
public:
    void foo() {}
    void bar() {}
};

bar実装が必要なクライアント コードは、 BarInterface.

于 2012-08-31T07:54:13.923 に答える
0

インターフェイスから D1 と D2 を継承すると仮定します。キャストを使用してベース ポインターを派生オブジェクトに変換し、それを使用できます。D2

于 2012-08-31T07:54:59.500 に答える
0
class _interface
{
    virtual void foo() = 0;
};

class _abstract : public _interface
{
public:
    _abstract(){}
    virtual ~_abstract(){};

    virtual void foo() = 0;
    int get_type()
    {
        return i_type;
    }

protected:
    int i_type;
};

class D1 : public _abstract
{
public:
    D1(){
        i_type = 1;
    }
    ~D1(){}

    void foo() {
        // do something
    }
};

class D2 : public _abstract
{
public:
    D2(){
        i_type = 2;
    }
    ~D2(){}

    void foo() {
        // do something
    }

    void bar() {
        // do something
    }
};
int main()
{
    D1 d_one;
    D2 d_two;

    _abstract* ab = &d_one;
    cout << ab->get_type() << "D1" << endl;

    ab = &d_two;
    cout << ab->get_type() << "D2" << endl;

    return 0;
}

get_type() によってどの子かを識別できます。これで、いつ bar() を使用できるかがわかります。私は最善のアプローチは何ですか。

于 2012-08-31T10:20:41.000 に答える