C++ 解决错误的方法:“无法实例化抽象类”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1699224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method for solving error: "cannot instantiate abstract class"
提问by max
I find one of the most time-consuming compiler errors for me is "cannot instantiate abstract class," since the problem is always that I didn't intend for the class to be abstract and the compiler doesn't list which functions are abstract. There's got to be a more intelligent way to solve these than reading the headers 10 times until I finally notice a missing "const" somewhere. How do you solve these?
我发现对我来说最耗时的编译器错误之一是“无法实例化抽象类”,因为问题始终是我不希望类是抽象的,并且编译器没有列出哪些函数是抽象的。必须有一种更聪明的方法来解决这些问题,而不是阅读标题 10 次,直到我终于注意到某处缺少“const”。你如何解决这些问题?
回答by James McNellis
cannot instantiate abstract class
无法实例化抽象类
Based on this error, my guess is that you are using Visual Studio (since that's what Visual C++ says when you try to instantiate an abstract class).
基于此错误,我猜测您正在使用 Visual Studio(因为当您尝试实例化抽象类时,Visual C++ 就是这样说的)。
Look at the Visual Studio Output window (View => Output); the output should include a statement after the error stating:
查看 Visual Studio 输出窗口(查看 => 输出);输出应在错误后包含一条语句,说明:
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'
(That is the error given for bdonlan's example code)
(这是 bdonlan 的示例代码给出的错误)
In Visual Studio, the "Error List" window only displays the first line of an error message.
在 Visual Studio 中,“错误列表”窗口仅显示错误消息的第一行。
回答by bdonlan
C++ tells you exactly which functions are abstract, and where they are declared:
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
So perhaps try compiling your code with C++, or specify your compiler so others can give useful suggestions for your specific compiler.
因此,也许尝试使用 C++ 编译您的代码,或者指定您的编译器,以便其他人可以为您的特定编译器提供有用的建议。
回答by Remy Lebeau
C++Builder tells you which method is abstract:
C++Builder 告诉你哪个方法是抽象的:
class foo {
virtual void x() const = 0;
};
class bar : public foo {
virtual void x() { }
};
new bar;
[BCC32 Error] File55.cpp(20): E2352 Cannot create instance of abstract class 'bar'
[BCC32 Error] File55.cpp(20): E2353 Class 'bar' is abstract because of 'foo::x() const = 0'