[英]cannot allocate an object of abstract type using inheritance, pure virtual methods
[英]Abstract Classes and virtual methods problems: “cannot allocate an object of abstract type”
我有这个课程:
class IDescriptor
{
public:
virtual float compare(IDescriptor *D) = 0;
};
class DescHistogram : public IDescriptor
{
public:
vector<float> desc;
DescHistogram(vector<float> vd);
~DescHistogram();
float compare(DescHistogram *D);
// ALL THESE FUNCTIONS ARE IMPLEMENTED IN THE SOURCE CPP FILE.
};
在我的代码中的某个地方,我做了这个初始化:
vector<float> hist;
[...] // filling the vector.
DescHistogram *myDesc = new DescHistogram(hist);
point.setDescriptor(myDesc);
编译器给我以下错误:
error: cannot allocate an object of abstract type ‘DescHistogram’
note: because the following virtual functions are pure within ‘DescHistogram’:
note: virtual float IDescriptor::compare(IDescriptor*)
我对此有一些疑问:
这个错误的原因是什么? 什么类型必须是DescHistogram::compare
的参数? 我明白它可以是派生类型,不是吗? 抽象类IDescriptor
需要构造函数吗?
也许这是一个愚蠢的错误,但我找不到任何解决方案。 在此先感谢您的帮助!
这个错误的原因是什么?
DescHistogram
不会覆盖IDescriptor::compare
与兼容函数IDescriptor::compare
,因此它仍然是抽象的,无法实例化。
什么类型必须是
DescHistogram::compare
的参数?
IDescriptor
,以匹配它覆盖的功能。 它必须可以使用基类函数接受的任何类型进行调用,因此不能是更多派生类型。
我明白它可以是派生类型,不是吗?
不,它必须是同一类型。
抽象类
IDescriptor
需要构造函数吗?
不。它已经有一个隐式的默认构造函数,并且不需要将任何其他东西作为非抽象派生类的一部分进行实例化。
您没有在DescHistogram
实现virtual compare()
函数 。 您实现了另一个compare()
函数:
virtual float compare(IDescriptor *D) = 0; // in class IDescriptor
float compare(DescHistogram *D); // in class DescHistogram
这个其他compare()
函数没有实现基类的virtual
函数,因此DescHistogram
仍然是抽象的。
如果从IDescriptor
派生的不同类型(如DescHistogram
)之间进行比较是没有意义的,那么你的代码设计是有缺陷的。 您仍然可以使用RTTI(即通过)获取代码
class DescHistogram : public IDescriptor
{
float compare_self(DescHistogram *D); // tolerates nullptr input
public:
float compare(IDescriptor *D)
{
return compare_self(dynamic_cast<DescHistogram*>(D));
}
};
但这可能效率低下。 此外, compare_self
没有明智的独立目的(由于设计缺陷)。
您需要在DescHistogram中定义比较功能
根据您在此处所写的内容,您可以为DescHistogram
定义compare
的DescHistogram
(并且还将其标记为纯virtual
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.