【问题标题】:how to Override operator <如何覆盖运算符 <
【发布时间】:2010-09-19 16:18:52
【问题描述】:

我正在尝试重写运算符

内部节点:

bool operator <(const Node* other) {
  return *(this->GetData()) < *(other->GetData());
}

车内:

bool operator <(const Vehicle &other) {
  return this->GetKilometersLeft() < other.GetKilometersLeft();
}

调用操作符:

while (index > 0 && m_heapVector[index] < m_heapVector[parent(index)])

向量定义:

vector<Node<T>*> m_heapVector;

我检查了调用,它没有调用被覆盖的运算符。

【问题讨论】:

    标签: c++ templates operators overriding


    【解决方案1】:

    这是因为你在比较指针,

    你必须成功:

    *m_heapVector[index] < *m_heapVector[parent(index)]
    

    并相应地调整运算符

    bool operator<(const Node &other) const;
    

    【讨论】:

    • 打败我。 “相应地调整运算符”意味着Node&lt;T&gt;::operator&lt;() 应该引用other,而不是指针。
    • @Ben 没问题,固定算子
    • @Roy,注意运算符应该是(const Node &amp;other)
    • @aaa 嘿,谢谢。我按照你说的做了,现在我的操作员看起来像这样: bool operator
    • @Roy 另一方面,我认为您的问题是您在比较运算符的实现中存在无限递归