【发布时间】:2014-03-28 16:34:31
【问题描述】:
标题很难清楚地说明主题,但我会尝试解释上下文(下面有一些代码)。注意:我已经看到回答了类似的问题,但他们只处理了 1 个子类的案例。所以他们对我的情况并没有真正的帮助,因为我有 2 个子类。
背景: 我有一个父类 Shape 有 2 个孩子:圆形和方形。 我将有一个 Shape 对象的向量,但这些 Shape 对象实际上只是 Circle 对象或 Square 对象。我需要 Circle 和 Square 类具有相同的父类,以便我可以将它们存储在同一个向量中。
诀窍是我需要使用向量中的 Shape 对象来调用在 Circle 类或 Square 类中实现的方法,因此,我需要在父类中拥有这些方法的“虚拟”版本形状。
这是我的类的代码的简化部分:
形状.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;
}
当我想创建 Circle 和 Square 对象时,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
看来我需要在 Square 类中声明“getRadius”,在 Circle 类中声明“getHeight”和“getWidth”...
我尝试使用虚拟添加它们,但这会使 Circle 和 Square 成为抽象类,因此我无法使用它们创建任何对象。
有没有办法让它工作?
这是我在 stackoverflow 上发布的第一个问题。我希望一切都清楚。感谢您的帮助!
【问题讨论】:
-
您必须至少为您在
Shape中声明的每个派生类中的纯虚函数定义一个主体,否则这些类将成为抽象基类并且无法实例化。 -
另外,你应该继承自
Shape而不是Shapes。 -
哎呀,我修好了。谢谢
-
不,这种设计尝试毫无意义,也没有办法添加任何东西。父类必须只具有所有子类通用的接口,句号,没有 ifs 或 buts 或但是。查找“is-a relationship”。
-
如上所述,您应该重新考虑您的设计,而不是试图让设计不佳的类进行编译。形状类应该只包含所有形状通用的成员。即使是一个空的基类也会比你现在的更好。
标签: c++ class inheritance polymorphism virtual