C++中抽象类(接口)的数组



我想声明一个接口数组,并进一步获得一个指向接口列表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指针数组,例如

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

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

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

最新更新