我正在从子类中的父类实现纯虚函数。
当我尝试在eclipse中实例化子类时,它说
'derived'类型必须实现继承的纯虚方法'Base :: compareTo'
我很确定我这样做了。我的基类是..
base.h
#ifndef BASE_H_
#define BASE
class Base{
public:
Base();
virtual ~Base();
virtual int compareTo(void* compare)=0;
};
#endif /* BASE*/
然后我的derived.h
#ifndef DERIVED_H_
#define DERIVED_H_
#include "Base.h"
class Derived : public Base {
public:
int x;
Derived(int y);
virtual ~Derived();
int compareTo(void* compare);
};
#endif /* DERIVED_H_ */
Derived.cpp
#include "Derived.h"
#include "Base.h"
Derived::Derived(int y) {
// TODO Auto-generated constructor stub
x=y;
}
Derived::~Derived() {
// TODO Auto-generated destructor stub
}
int Derived::compareTo(void* compare) {
Derived* compared;
int result=0;
if(compared=dynamic_cast<Derived*>(compare))
{
if(x<compared->x)
{
result=-1;
}
else
{
result=1;
}
}
return result;
}
答案 0 :(得分:1)
我假设此消息来自eclipses代码分析器,而不是来自编译器。代码分析器是错误的,你是对的。您已在Derived
中的基类中正确实现了纯虚方法。如果您尝试实例化Derived,则代码应该编译。
您的CDT版本可能低于8.2.1吗?如果是这样,您可能会遇到this bug,应该在8.2.1中修复。
但是您的代码中还有另一个错误。你不能dynamic_cast一个void指针。
答案 1 :(得分:0)
尝试这个基类代码:
#ifndef BASE_H_
#define BASE_H_
class Base{
public:
//Base (); not needed in the virtual class
virtual ~Base() {};
virtual int compareTo(void* compare)=0;
};
#endif /* BASE*/
#ifndef DERIVED_H_
#define DERIVED_H_
#include "Base.h"
class Derived : public Base {
public:
int x;
Derived(int y);
virtual ~Derived();
int compareTo(void* compare) override/*C++11*/;
};
#endif /* DERIVED_H_ */
#include "Derived.h"
//#include "Base.h" Not needed
Derived::Derived(int y) {
// TODO Auto-generated constructor stub
x=y;
}
Derived::~Derived() {
// TODO Auto-generated destructor stub
}
int Derived::compareTo(void* compare) {
Derived* compared;
int result=0;
if(compared=dynamic_cast<Derived*>(compare))
{
if(x<compared->x)
{
result=-1;
}
else
{
result=1;
}
}
return result;
}