【问题标题】:C++ multiple inheritance problem using FLTK使用 FLTK 的 C++ 多继承问题
【发布时间】:2022-01-12 15:51:59
【问题描述】:

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

我已经制作了 2 个可以正常显示的类“矩形”和“圆形”。然后我创建了第三个类,它继承自 '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 类中创建了一个 'RectangleAndCircle' 的实例,然后绘制它。

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

我做错了吗?

【问题讨论】:

    标签: c++ oop fltk


    【解决方案1】:

    您正在使用虚拟继承。这意味着在RectangleAndCircle 中将只有一个BasicShape 实例。这个BasicShapefillColor 将由RectangleCircle 构造函数设置,无论哪个最后被调用,都会覆盖该值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-23
      • 2012-05-11
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多