从struct调用函数

时间:2015-01-01 17:57:08

标签: c++ struct

获取错误 需要帮助

struct Point  {
        double x , y ;
        double del ;
        Point () {}
        Point (double _x , double _y){ x = _x; y = _y;}

        double Dist(const Point &P){ double dx = x - P.x ; double dy = y - P.y; return sqrt(dx*dx + dy *dy);}

};

int ccw ( Point p,Point q ,Point r)
{

        double val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);


        if( fabs(val) < EPS) return 0;
        if( val > EPS ) return  1;
        else return 2 ;

}

struct seg2 {
        Point a,  b;
        seg2(){}
        seg2(Point _a ,Point _b){a = _a;b= _b;}
        double length(){ return a.Dist(b);}
        bool onseg( const Point &p) {
                return (a.Dist(p) + b.Dist(p) - length() < 0);
        }
        bool isIntersect (const seg2& S){
                int o1 = ccw(a, b, S.a);
                int o2 = ccw(a, b, S.b);
                int o3 = ccw(S.a, S.b, a);
                int o4 = ccw(S.a, S.b, b);

                if( o1 != o2 && o3 != o4){
                        return true;
                }
                if(o1 == 0 && onseg(S.a)) return true;
                if(o2 == 0 && onseg(S.b)) return true;

                if(o3 == 0 && S.onseg(a)) return true; // Here I want to call S.onseg
                if(o4 == 0 && S.onseg(b)) return true; // Here 
                return false;
        }


};

我收到此错误

member function 'onseg' not viable: 'this' argument has type 'const seg2',
      but function is not marked const
                if(o3 == 0 && S.onseg(a)) return true;

'onseg' declared here
        bool onseg( const Point &p) {

member function 'onseg' not viable: 'this' argument has type 'const seg2',
      but function is not marked const
                if(o4 == 0 && S.onseg(b)) return true;

'onseg' declared here
        bool onseg( const Point &p) {

这是两个线段相交或不相交的程序 但我无法从结构中调用onseg函数 :( C ++代码.. 这给了我编译错误.. 我怎么称呼?

1 个答案:

答案 0 :(得分:0)

bool isIntersect (const seg2& S){

S被声明为const,然后您尝试在其上调用non-const函数: -

S.onseg(a); <<<< `non-const` function.

将您的功能定义更改为: -

bool onseg( const Point &p) const              <<<<<<<<<  const added
{
    return (a.Dist(p) + b.Dist(p) - length() < 0);
}

const以及non-const对象调用此方法。

相关问题