很难使标题明确清晰,但我会尝试解释上下文(以及下面的一些代码)。注:我看过类似的问题,但他们只处理1个孩子的情况。所以他们对我的情况并没有真正的帮助,因为我有两个孩子班。C++在两个不同的子类中实现了虚拟方法的父类
上下文: 我有一个父类有2个孩子的形状:圆形和正方形。 我将有一个Shape对象的向量,但这些Shape对象实际上只能是Circle对象或Square对象。我需要Circle和Square类具有相同的父类,以便我可以将它们存储在同一个向量中。
诀窍是我需要使用矢量中的Shape对象来调用在Circle类或Square类中实现的方法,因此,我需要在父类中有一个“虚拟”版本的方法类形状。
下面是代码为我班的简化部分:
Shape.h:
class Shape{
public:
std::string getColor();
virtual int getRadius() = 0; //Method implemented in Circle
virtual int getHeight() = 0; //Method implemented in Square
virtual int getWidth() = 0; //Method implemented in Square
protected:
std::string color;
};
class Circle : public Shape{
public:
int getRadius();
private:
int radius;
};
class Square : public Shape{
public:
int getHeight();
int getWidth();
private:
int height;
int width;
};
在Shape.cpp我有这样的事情:
std::string Shape::getColor(){
return color;
}
int Circle::getRadius(){
return radius;
}
int Square::getHeight(){
return height;
}
int Square::getWidth(){
return width;
}
错误发生在main.cpp中,当我想创建圆形和方形对象时:
Circle *c = new Circle(...);//Error: cannot instantiate abstract class
//pure virtual function "Shape::getHeight" has no overrider
//pure virtual function "Shape::getWidth" has no overrider
Square *s = new Square(...);//Error: cannot instantiate abstract class
//pure virtual function "Shape::getRadius" has no overrider
所以好像我需要“getRadius”在Square类的声明和“的getHeight”和“的getWidth”在Circle类的声明...
我尝试添加他们与虚拟,但这使得圆形和方形抽象类,所以我不能与他们创建任何对象。
有没有办法让这项工作?
这是我发布在stackoverflow的第一个问题。我希望一切都很清楚。谢谢您的帮助!
您必须至少为您在每个派生类中的Shape中声明的纯虚函数定义一个主体,或者这些类变为抽象基类并且不能实例化。 – larrylampco
另外,你应该从'Shape'继承而不是'Shapes'。 – larrylampco
Oups,我修好了。谢谢 – JLuc5