如何在C ++中正确地将接口委托给姐妹类?

时间:2017-10-01 13:43:51

标签: c++ class oop inheritance virtual-method

我们假设我有ChildParent类,其中Child扩展了Parent

class Parent {
    void foo() {cout << "foo\n";}
    void bar() {cout << "bar\n";}
    void jar() {cout << "jar\n";}
};

class Child: public Parent {
    void child_method1();
    void child_method2();
};

现在我想使用以下界面导出一些Child功能:

class Interface {
public:
    virtual ~Interface(){}

    virtual void foo() = 0;
    virtual void bar() = 0;

protected:
    Interface(){}
};

正如您所看到的,接口方法已在Parent中实现。如何正确定义Child以便将Interface委托给Parent

我试图这样做:

class Child: public Parent, public Interface {
    void child_method1();
    void child_method2();
}

但编译器抱怨虚拟方法foo()bar()未在Child中实现。

如果我写这样一个明确的代表团:

class Child: public Parent, public Interface {
    void foo() {Parent::foo();}
    void bar() {Parent::bar();}

    void child_method1();
    void child_method2();
}

编译器没有抱怨。 是否有必要编写显式委托?将虚方法委托给姐妹班的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

  

是否有必要编写显式委托?

是的,否则您将收到编译错误。

  

什么是正确的方法?

停在那里并重新考虑你的设计。

为什么在派生类中不需要覆盖这些函数时,将函数标记为virtual

你可以直接传递对父类的引用,而不是使用现在似乎没用的接口。