C++ “无法分配抽象类型的对象”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7352706/
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
"Cannot allocate an object of abstract type" error
提问by Itzik984
Error is here:
错误在这里:
vector<Graduate *> graduates;
graduates.push_back(new AliceUniversity(identifier,id,salary,average));
Grandparent class:
祖父母类:
Graduate::Graduate(char identifier,
long id,
int salary,
double average)
: _identifier(identifier),
_id(id),_salary(salary),
_average(average)
{
}
Parent class:
父类:
UniversityGraduate::UniversityGraduate(char identifier,
long id,
int salary,
double average)
: Graduate(identifier,id,salary,average)
{
}
Actual/child class:
实际/子类:
AliceUniversity::AliceUniversity(char identifier,
long id,
int salary,
double average)
: UniversityGraduate(identifier,id,salary,average)
{
_graduateNum++;
_sumOfGrades += average;
_avrA = getAverage();
}
I know it's a long shot, I cant write the entire code here…
我知道这是一个长镜头,我不能在这里写整个代码......
回答by Alok Save
In C++ a class with at least one pure virtual functionis called abstract class. You can not create objects of that class, but may only have pointers or references to it.
在 C++ 中,具有至少一个纯虚函数的类称为抽象类。您不能创建该类的对象,但可能只有指向它的指针或引用。
If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.
如果您是从抽象类派生的,那么请确保为您的类覆盖和定义所有纯虚函数。
From your snippet Your class AliceUniversity
seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate
and UniversityGraduate
.
从你的片段你的类AliceUniversity
似乎是一个抽象类。它需要覆盖和定义类Graduate
和UniversityGraduate
.
Pure virtual functions are the ones with = 0;
at the end of declaration.
纯虚函数是= 0;
声明末尾的函数。
Example: virtual void doSomething() = 0;
例子: virtual void doSomething() = 0;
For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.
对于特定的答案,您需要发布您收到错误的类的定义以及该类派生自的类。
回答by Daniel
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
您必须在其中一个父类中声明一些虚函数,并且从未在任何子类中实现。确保所有虚函数都在继承链中的某处实现。如果类的定义包含从未实现的纯虚函数,则永远无法构造该类的实例。