c++ 接口和多重继承

pqwbnv8z  于 2023-05-30  发布在  其他
关注(0)|答案(2)|浏览(160)

我想把我的代码设计成微软的COM,意思是:

  • 我有我的dll,其中有不同的对象实现不同的接口
  • 我只向客户端公开了接口(这部分在这里不是一个真正的问题,只是为了给予更多的上下文)。

现在作为一个例子,以这段代码为例(你可以在这里运行它https://onlinegdb.com/Z7RPQVrCZ):

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

class IChild : public IParent
{
public:
    virtual void bar() const = 0;  
};

class Parent : public IParent
{
private:
        int a_;
        
public:
    virtual void foo() const override { /* for ex: do something with a_ */ }
};

class Child : public IChild, public Parent
{
public:
    virtual void bar() const override {}
    
    // My issue is here:
    using Parent::foo;
};

int main()
{
    Child c;
    return 0;
}

我得到编译错误:
main.cpp:38:11: error: cannot declare variable ‘c’ to be of abstract type ‘Child’
如果我将using Parent::foo;替换为:
virtual void foo() const override { return Parent::foo(); }
正常编译。但这又有什么意义呢?我不想推翻它。在某种程度上,我甚至想使Parent::foofinal例如。
我想问题是Child继承自IChildParent,而这两者都继承自IParent。但随后:

  • 为什么explicit using不起作用?
  • 如果它是什么,这是否意味着这个设计只是不符合我的需要在这里?
  • 或者我只是执行得不好?
gzjq41n4

gzjq41n41#

使用继承避免菱形的(crtp)mixin示例。通过这种方式,继承被用来聚合具有多个“基”行为的类中的功能。

#include <iostream>

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

class bar_itf
{
    virtual void bar() = 0;
};

// do NOT put reusable code in a baseclass
// but in a mixin class
template<typename class_t>
class foo_impl :
    public foo_itf
{
public:
    void foo() override
    {
        std::cout << "foo\n";
    }
};

template<typename class_t>
class bar_impl :
    public bar_itf
{
public:
    void bar() override
    {
        std::cout << "bar\n";
    }
};

// "left diamond" class replacement
class foo_t :
    public foo_impl<foo_t>
{
};

// "right diamond" class replacement
class bar_t :
    public bar_impl<bar_t>
{
};

// class that can do both
// but is NOT derived from a common single parent class
// so there is no diamond.
class foo_bar_t :
    public foo_impl<foo_bar_t>,
    public bar_impl<foo_bar_t>
{
};

int main()
{
    foo_t foo;
    bar_t bar;
    foo_bar_t foobar;

    foo.foo();
    bar.bar();

    foobar.foo();
    foobar.bar();

    return 0;
}
iyr7buue

iyr7buue2#

添加虚拟实际上有效。

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

class IChild : virtual public IParent
{
public:
    virtual void bar() const = 0;  
};

class Parent : virtual public IParent
{
private:
        int a_;
        
public:
    virtual void foo() const override { /* for ex: do something with a_ */ }
};

class Child : public IChild, public Parent
{
public:
    virtual void bar() const override {}
    
    //My issue is here:
    
    // This raise compile error "Child is abstract"
    using Parent::foo;
    
    // This works, but I don't like it much...
    // virtual void foo() const override { return Parent::foo(); }
};

int main()
{
    Child c;
    return 0;
}

相关问题