【问题标题】:Array of abstract classes (interfaces) in C++C++ 中的抽象类(接口)数组
【发布时间】:2021-04-14 23:03:12
【问题描述】:

我想声明一个接口数组并进一步获取指向接口列表Interface* 的指针。但是编译器 (GCC) 打印错误 error: invalid abstract 'type Interface' for 'array'。代码:

class Interface {
public:
    virtual ~Interface() = default;

    virtual void Method() = 0;
};

class Implementation : public Interface {
public:
    void Method() override {
        // ...
    }
};

class ImplementationNumberTwo : public Interface {
public:
    void Method() override {
        // ...
    }
};

// there is an error
static const Interface array[] = {
        Implementation(),
        ImplementationNumberTwo(),
        Implementation()
};

我该如何解决?

【问题讨论】:

  • 定义Interface 的数组要求Interface 可以被实例化。这不可以。你需要一个指针数组(例如Interface *)或智能指针(例如std::unique_ptr<Interface>)。我将把初始化作为一个练习 - 但它会与您尝试的不同。

标签: c++ gcc interface compiler-errors


【解决方案1】:

您不能创建 Interface 对象,因为它是抽象类型。即使Interface 不是抽象的,由于object slicing,你正在尝试的东西也不会起作用。相反,您需要创建一个 Interface 指针数组,例如

static Interface* const array[] = {
    new Implementation(),
    new ImplementationNumberTwo(),
    new Implementation()
};

在 C++ 中,多态性只能通过指针(或引用)起作用。

当然,使用动态分配来创建 Interface 对象会带来新问题,例如这些对象如何被删除,但这是一个单独的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2018-07-17
    • 2011-05-22
    • 1970-01-01
    • 2013-12-31
    • 2012-10-03
    • 2011-01-19
    相关资源
    最近更新 更多