使用FLTK的C++多重继承问题



我在用fltk绘制基本形状时遇到问题。

我已经做了两个类"矩形"one_answers"圆形",正常显示。然后我创建了第三个类,它继承了"Rectangle"one_answers"Circle",称为"RectangleAndCircle":

//declaration in BasicShape.h
class Rectangle: public virtual BasicShape, public  virtual Sketchable{
int w,h;
public:
Rectangle(Point center, int width=50, int height=50, Fl_Color fillColor=FL_WHITE, Fl_Color frameColor=FL_BLACK);
void setPoint(Point new_p){center=new_p;}
virtual void draw() const override;
};
class Circle:public virtual BasicShape, public  virtual Sketchable{
int r;
public:
Circle(Point center, int rayon=50, Fl_Color fillColor=FL_WHITE, Fl_Color frameColor=FL_BLACK);
virtual void draw() const override;
};
class RectangleAndCircle: public virtual Rectangle, public virtual Circle{
public:
RectangleAndCircle(Point center,int w, int h, int r,
Fl_Color CircFillColor, Fl_Color CircFrameColor,
Fl_Color RectFillColor, Fl_Color RectFrameColor);
void draw() const override;

当我尝试绘制"RectangleAndCircle"实例时,即使设置了矩形颜色,矩形和圆形也共享相同的颜色。

以下是"RectangleAndCircle"的构造函数和形状的绘制代码:

RectangleAndCircle::RectangleAndCircle(Point center, int w, int h, int r, Fl_Color CircFillColor,
Fl_Color CircFrameColor, Fl_Color RectFillColor, Fl_Color RectFrameColor)
:Rectangle(center,w,h,RectFillColor,RectFrameColor)
, Circle(center,r,CircFillColor,CircFrameColor){}

void Rectangle::draw() const {
fl_begin_polygon();
fl_draw_box(FL_FLAT_BOX, center.x+w/2, center.y+h/2, w, h, fillColor);
fl_draw_box(FL_BORDER_FRAME, center.x+w/2, center.y+h/2, w, h, frameColor);
fl_end_polygon();
}
void Circle::draw() const {
fl_color(fillColor);
fl_begin_polygon();
fl_circle(center.x, center.y, r);
fl_end_polygon();
}
void RectangleAndCircle::draw() const {
Rectangle::draw();
Circle::draw();
}

我在MainWindow类中创建了一个"RectangleAndCircle"的实例,并绘制了它

RectangleAndCircle r{Point{50,50},50,50,12,FL_RED,FL_BLACK, FL_WHITE, FL_BLACK};
...
r.draw()

我做错什么了吗?

您使用的是虚拟继承。这意味着RectangleAndCircle中只有一个BasicShape实例。此BasicShapefillColor将由RectangleCircle构造函数设置,无论调用的是最后一个重写值的构造函数。

我的建议是不要在这里继承,而是在RectangleAndCricle中有两个类型为CircleRectangle的字段,然后在draw中分别调用draw。继承以重用,而不是重用(您可能不想将RectangleAndCricle作为CircleRectangle传递(