【问题标题】:Problem with operator <运算符 < 的问题
【发布时间】:2010-09-21 10:38:15
【问题描述】:

我写的操作符

在 Node.h 中:

.
..
bool operator<(const Node<T>& other) const;
const T& GetData ();
.
..
template <class T>
const T& Node<T>::GetData () {
 return m_data;
}

template <class T>
bool Node<T>:: operator<(const Node<T>& other) const
{
 return (*(this->GetData()) < *(other.GetData()));
}

在 Heap.h 中:

template<class T>
void Heap<T>::Insert(Node<T>* newNode) {
 if (m_heap.size() == 0) {
  m_heap.push_back(newNode);
 }
 else
  DecreaseKey(newNode);  
}

template<class T>
void Heap<T>::DecreaseKey(Node<T>* newNode) {
 m_heap.push_back(newNode);
 int index = m_heap.size();
 while ((index > 1) && (m_heap[(index/2)-1] < (m_heap[index-1]))) { // doen't do the operator < !
  Exchange(index,index/2);
  index = index/2;
 }
}

在 Vehicle.h 中:

bool operator< (const Vehicle& otherVehicle) const;

在 Vehicle.cpp 中:

bool Vehicle::operator<(const Vehicle& otherVehicle) const {
 return (GetDistance() > otherVehicle.GetDistance());
}

在 main.cpp 中: .

..
 Node<Vehicle*> a(car1);
 Node<Vehicle*> b(car2);
 Heap<Vehicle*> heap;
 Node<Vehicle*>* p = &a;
 Node<Vehicle*>* q = &b;
 heap.Insert(p);
 heap.Insert(q);
 heap.ExtractMin()->GetData()->Show();
.
..

为什么它不做比较?使用运算符

【问题讨论】:

  • 请尽量减少发布代码。如果您在所有代码上方陈述您的问题,它对阅读有很大帮助。

标签: c++ operator-overloading


【解决方案1】:

m_heap 是一个指针容器。在这种情况下,您应该取消引用节点指针:

while ((index > 1) && (*m_heap[(index/2)-1] < (*m_heap[index-1])))

现在应该为 Nodes 调用 operator&lt;,而 Nodes 又为 Vehicles 调用 operator&lt;

【讨论】:

    【解决方案2】:

    因为您使用的是 Vehicle*,而不是 Vehicle。

    【讨论】:

    • 为 Vehicle* 创建一个包装类并存储/比较它们。
    • @Gil:不,你创建了一个适用于 Vehicle 的类。你从来没有写过代码来处理所讨论的类型是指针类型的情况。
    【解决方案3】:

    使用 std::priority_queue 代替堆,或任何其他允许您定义自定义比较谓词的堆。

    【讨论】:

      【解决方案4】:

      从我看到的 m_heap 存储指向节点的指针

       while ((index > 1) && (m_heap[(index/2)-1] < (m_heap[index-1]))) { // doen't do the operator < 
      

      我想应该这样做

      while ((index > 1) && (*(m_heap[(index/2)-1]) < *(m_heap[index-1]))) {
      

      【讨论】:

      • O.k ... 现在它会出错 C662: 'Node::GetData' : cannot convert 'this' pointer form 'const Node' to 'Node&'
      • 用 const => "const T& Node::GetData () const" 声明 GetData
      【解决方案5】:

      简短回答:不要使用指针。您可能不需要它们。

      如果可能,如果您使用普通对象,则更容易使此类代码正确。如果您需要使用指针的概念,请使用指针容器类,即作为具有值语义和潜在自定义重载的普通对象传递的包装器,例如您正在使用的 operator

      这样,您不需要在整个应用程序中处理指针,而只需要在语义相关的地方处理。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-24
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 2011-10-20
        • 1970-01-01
        相关资源
        最近更新 更多