C++ C+中的抽象类(接口)数组+;
我想声明一个接口数组,并进一步获取一个指向接口列表的指针C++ C+中的抽象类(接口)数组+;,c++,gcc,interface,compiler-errors,C++,Gcc,Interface,Compiler Errors,我想声明一个接口数组,并进一步获取一个指向接口列表的指针Interface*。但是编译器(GCC)打印错误错误:“数组”的抽象“类型接口”无效。。代码: class Interface { public: virtual ~Interface() = default; virtual void Method() = 0; }; class Implementation : public Interface { public: void Method() overrid
Interface*
。但是编译器(GCC
)打印错误错误:“数组”的抽象“类型接口”无效。
。代码:
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()
};
如何解决它?您不能创建
接口
对象,因为它是抽象类型。即使接口
不是抽象的,您正在尝试的内容也不会工作,因为。相反,您需要创建一个接口指针数组,例如
static Interface* const array[] = {
new Implementation(),
new ImplementationNumberTwo(),
new Implementation()
};
C++中的多态性仅通过指针(或引用)工作。
当然,使用动态分配来创建接口
对象会带来新的问题,比如如何删除这些对象,但这是一个单独的问题。您不能创建接口
对象,因为它是一种抽象类型。即使接口
不是抽象的,您正在尝试的内容也不会工作,因为。相反,您需要创建一个接口指针数组,例如
static Interface* const array[] = {
new Implementation(),
new ImplementationNumberTwo(),
new Implementation()
};
C++中的多态性仅通过指针(或引用)工作。
当然,使用动态分配来创建接口
对象会带来新的问题,比如如何删除这些对象,但这是一个单独的问题。定义接口
数组需要可以实例化接口
。它不能。您需要一组指针(例如Interface*
)或智能指针(例如std::unique_ptr
)。我将把初始化留作练习-但它与您尝试的不同。定义接口
数组需要可以实例化接口
。它不能。您需要一组指针(例如Interface*
)或智能指针(例如std::unique_ptr
)。我将把初始化作为一个练习,但它与您正在尝试的不同。