C++ 中的抽象数组 类(接口)
Array of abstract classes (interfaces) in 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
不是抽象的,你正在尝试的也不会因为 object slicing 而起作用。相反,您需要创建一个 Interface
指针数组,例如
static Interface* const array[] = {
new Implementation(),
new ImplementationNumberTwo(),
new Implementation()
};
在 C++ 中,多态性只能通过指针(或引用)起作用。
当然,使用动态分配创建 Interface
对象会带来新问题,例如这些对象如何被删除,但这是一个单独的问题。
我想声明一个接口数组,并进一步获取指向接口列表的指针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
不是抽象的,你正在尝试的也不会因为 object slicing 而起作用。相反,您需要创建一个 Interface
指针数组,例如
static Interface* const array[] = {
new Implementation(),
new ImplementationNumberTwo(),
new Implementation()
};
在 C++ 中,多态性只能通过指针(或引用)起作用。
当然,使用动态分配创建 Interface
对象会带来新问题,例如这些对象如何被删除,但这是一个单独的问题。