c++ - 如何覆盖运算符 <

标签 c++ templates operators overriding

我正在尝试重写运算符<,如下所示:

节点内部:

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 定义:

vector<Node<T>*> m_heapVector;

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

最佳答案

这是因为您正在比较指针,

你必须做到:

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

并相应地调整运算符

bool operator<(const Node &other) const;

关于c++ - 如何覆盖运算符 <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3746462/

相关文章:

c++ - 我的编译器有多聪明?

c++ - 使用继承的 luabind 和 std::shared_ptr

c++ - 如何编写 boost::spirit::qi 解析器来执行 '?' 在正则表达式中所做的事情?

c++ - 不允许使用多个模板参数列表

ruby - ==~ 运算符是做什么的?

c++ - 无法使用模板让此类工作吗?

c++ - 使用函数参数的模板参数编写函数

c++ - 在 C++1z 中声明友元模板类模板产生错误 : specialization of ‘template<class T> class A’ must appear at namespace

c# - Python 的 'in' 运算符相当于 C#

python - 为什么 Python 将加法运算符的连续重复视为单次重复?