接口的实现

时间:2012-08-31 07:50:33

标签: c++ oop interface implementation

我有一个接口和一些实现。但是在一个实现中,我只使用了该实现中的指定功能。

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

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

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

所以我只在D2中有一个D2 :: bar()函数,它只为D2实现指定。 使用OOP写这种东西的正确方法是什么?

在我的客户端代码中,我有一个电话: 接口* i; 异> FOO();

但如果它是“i”中的D2,我需要在某些情况下调用bar()函数。

5 个答案:

答案 0 :(得分:1)

如果你需要调用bar函数,你需要引用一个知道bar的对象。

因此,要么引用D2对象,要么接口必须包含bar函数。在后一种情况下,您的D1也必须实现它,但实现可以为空或返回错误值。

答案 1 :(得分: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

答案 2 :(得分:0)

假设您从Interface继承D1和D2。你可以使用强制转换将基指针转换为派生对象并使用它,只要基指针指向D2

答案 3 :(得分: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;异>巴();如果我是D1,它什么都不做,如果我是D2,它会做D2特定的事情。

答案 4 :(得分: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()。我不知道什么是最好的方法。

相关问题