【发布时间】: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