[英]C++ multiple inheritance problem using FLTK
我在用 fltk 绘制基本形状时遇到问题。
我制作了 2 个可以正常显示的类“矩形”和“圆形”。 然后我创建了第三个 class,它继承自“Rectangle”和“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 class 中创建了一个“RectangleAndCircle”的实例,然后绘制它。
RectangleAndCircle r{Point{50,50},50,50,12,FL_RED,FL_BLACK, FL_WHITE, FL_BLACK};
...
r.draw()
难道我做错了什么?
您正在使用虚拟 inheritance。 这意味着RectangleAndCircle
中只有一个BasicShape
实例。 这个BasicShape
的fillColor
将由Rectangle
和Circle
构造函数设置,无论哪个最后被调用,都会覆盖该值。
我的建议是不要在这里继承,而是在RectangleAndCricle
中有两个Circle
和Rectangle
类型的字段,然后在draw
中分别调用这些字段。 继承要重用,而不是重用(您可能不想将RectangleAndCricle
作为Circle
或Rectangle
传递)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.