理解常量表达式错误

时间:2013-12-10 10:30:36

标签: c++

我有兴趣了解以下错误的来源:

  

''不能出现在常量表达式

由于这个链接,我已经知道如何解决这个问题:'.' and constant-expression

事实上,我遇到的问题与上面链接中描述的问题相同。 我只是想了解为什么恢复比较会使它工作。 谢谢。 这是我的代码:

template <typename Key> std::vector<Segment<Key> > findIntersections(const Interval<Key> &interval ,Segment<Key> segment)
{
Interval<Key> *x = &interval;
vector<Segment<Key> > intersections;

while( x!= NULL)
{
    if(x->intersects(segment.gety1(),segment.gety2())) intersections.push_back(segment);
    else if (x->left == NULL)                x = x->right;
    //else if (x->left->max < segment.gety1()) x = x->right;//this line gives the error
    else if (segment.gety1() > x->left->max) x = x->right;//this line is OK
    else                                     x = x->left;
}
return intersections;
}

EDIT1

我在下面的代码中提供了更多代码。

Interval<Key>

定义几何区间(不要注意评论):

template <class Key> class Interval
{
public:
    Key low;
    //Key high;//previous implementation
    std::vector<Key> high;//to implement... may be better to use a max priority queue
                          //A priority queue is better since accessing a value is in o(log N) - vector is in o(N)
                          //as well deleting and inserting is in o(log N) for priority queue
                          //a binary tree is good as well.
    Key max;//to implement
    Key back;//represent the maximum of the list of high
    bool color;
    int N; //number of nodes under this subtree
    Interval *left, *right;
    Interval(Key lo, Key hi, Key val, bool c): low(lo),max(val),back(val),color(c),N(1),left(NULL),right(NULL)
    {
        high.push_back(hi);
    }
    bool intersects(Key lo, Key hi);
};

Segment类:

template <class Type> class Segment
{
private:
    Type x1, y1, x2, y2;

public:
    Segment(Type x1, Type y1, Type x2, Type y2):x1(x1), y1(y1), x2(x2), y2(y2){}
    inline bool isHorizontal(){return x1 == x2;}
    inline bool isVertical  (){return y1 == y2;}
    int compare(Segment segment);
    inline Type getx1(){return x1;}
    inline Type getx2(){return x2;}
    inline Type gety1(){return y1;}
    inline Type gety2(){return y2;}

};

最后是交叉方法:

template <class Key> bool Interval<Key>::intersects(Key lo, Key hi)
{
if(lo <= this->low && this->back <= hi) return true;
if(this->low <= lo && hi <= this->back) return true;
if(lo <= this->low && hi <= this->back) return true;
if(this->low <= lo && this->back <= hi) return true;
return false;

} 

如果您需要更多,请告诉我...... 谢谢大家的帮助......

EDIT2

我正在为windows使用gcc 4.6.1编译器:MinGW-32位

2 个答案:

答案 0 :(得分:2)

您的代码中是using namespace std;吗?这是唯一的方法,我可以重现你的错误。见here。看起来,编译器将max视为模板函数,因此将<视为参数列表的开头。

PS:您的代码在 MSVC 2013 Express 中运行良好,无论代码中是否有using namespace std

link可能会更多地解释您的问题。

答案 1 :(得分:0)

似乎编译器以某种方式(宏观巫术似乎最有可能)诱导认为<标识符后面的max符号不是比较运算符而是开放模板参数列表括号。因此,必须的内容必须是类型名称或常量表达式。