Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C+中的抽象类(接口)数组+;_C++_Gcc_Interface_Compiler Errors - Fatal编程技术网

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
)。我将把初始化作为一个练习,但它与您正在尝试的不同。