我在用 fltk 繪制基本形狀時遇到問題。
我制作了兩個正常顯示的類“矩形”和“圓”。然后我創建了從 '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()
難道我做錯了什么 ?
uj5u.com熱心網友回復:
您正在使用虛擬繼承。這意味著將只有一個BasicShapein實體RectangleAndCircle。這BasicShape將由fillColortheRectangle和Circle建構式設定,以最后呼叫的那個覆寫該值。
我的建議是不要在這里繼承,而是有兩個 typeCircle和Rectanglein欄位,RectangleAndCricle然后分別在draw. 繼承以重用,而不是重用(您大概不想將 aRectangleAndCricle作為 aCircle或傳遞Rectangle)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/375668.html
上一篇:回傳兩個串列的所有可能組合
