解决错误的方法:"无法实例化抽象类"

max*_*max 13 c++ compiler-errors

我发现对我来说最耗时的编译器错误之一是"无法实例化抽象类",因为问题始终是我不打算让类是抽象的,编译器不会列出哪些函数是抽象的.必须有一种更聪明的方法来解决这些问题,而不是阅读标题10次,直到我最终注意到某个地方缺少"const".你是如何解决这些问题的?

Jam*_*lis 45

无法实例化抽象类

基于此错误,我的猜测是您正在使用Visual Studio(因为这是Visual C++在您尝试实例化抽象类时所说的).

查看Visual Studio输出窗口(View => Output); 输出应包含错误说明后的语句:

stubby.cpp(10) : error C2259: 'bar' : cannot instantiate abstract class
due to following members:
'void foo::x(void) const' : is abstract
stubby.cpp(2) : see declaration of 'foo::x'
Run Code Online (Sandbox Code Playgroud)

(这是bdonlan的示例代码给出的错误)

在Visual Studio中,"错误列表"窗口仅显示错误消息的第一行.


bdo*_*lan 6

C++确切地告诉您哪些函数是抽象的,以及它们的声明位置:

class foo {
        virtual void x() const = 0;
};

class bar : public foo {
        virtual void x() { }
};

void test() {
        new bar;
}

test.cpp: In function ‘void test()’:
test.cpp:10: error: cannot allocate an object of abstract type ‘bar’
test.cpp:5: note:   because the following virtual functions are pure within ‘bar’:
test.cpp:2: note:       virtual void foo::x() const
Run Code Online (Sandbox Code Playgroud)

因此,或许尝试使用C++编译代码,或者指定编译器,以便其他人可以为您的特定编译器提供有用的建议.