问题覆盖 c++ class 以绘制曲线

Issue overriding c++ class for drawing curve

我正在尝试实现一个程序,当用户点击屏幕时,该程序会点对点绘制线条。我有一条折线 class,它是自由形式 class 的子 class,是曲线 class 的子class。 Curve superclass 的draw 方法通常调用getPoint,它会在该特定点获得曲线的加权点。但是,对于 Polyline 的绘制方法,我试图覆盖曲线 class 以仅获取用户单击的点(如您所见,Polyline [= 的绘制方法14=] 从不调用 getPoint)。但是,当我调试代码时,我发现在尝试绘制多段线时仍在调用 getPoint。有什么建议吗?

class Curve {

public:
    virtual float2 getPoint(float t)=0;

    void draw(){

        glBegin(GL_LINE_STRIP);
        for (float i = 0; i < 1; i+=.01) {
            float2 point = getPoint(i);
            float x = point.x;
            float y = point.y;
            glVertex2d(x, y);

        }
        glEnd();
        }; 
    };

class Freeform : public Curve
{
protected:
    std::vector<float2> controlPoints;

public:
    virtual float2 getPoint(float t)=0;
    virtual void addControlPoint(float2 p)
    {
        controlPoints.push_back(p);
    }
    void drawControlPoints(){
        glBegin(GL_POINTS);
        for (float i = 0; i < controlPoints.size(); i++) {
            float2 point = controlPoints.at(i);
            float x = point.x;
            float y = point.y;
            glVertex2d(x, y);

        }
        glEnd();// draw points at control points
    }
};

class Polyline : public Freeform {
public:
    float2 getPoint(float t) {
        return float2(0.0, 0.0);
    }
    //we add a control point (in this case, control point is where mouse is clicked)
    void addControlPoint(float2 p)
    {
        controlPoints.push_back(p);
    }
    //trying to override Curve draw method
    void draw(){
        glBegin(GL_LINE_STRIP);
            for (float i = 0; i < controlPoints.size(); i++) {
            float2 point = controlPoints.at(i);
            float x = point.x;
            float y = point.y;
            glVertex2d(x, y);
        }
        glEnd();
    };
};
//trying to override Curve draw method

上面的评论几乎说明了一切;您正在 “尝试” 覆盖 void Curve::draw (),但未能这样做,因为 成员函数 之前未声明 [​​=12 =].


解决方案

  • void Curve::draw () 声明为 virtual
  • 如果 or later, look into (and make use of) the keyword override.