我写的运算符
在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();
.
..
为什么不竞争?使用opeartor
最佳答案
因为您使用的是Vehicle *,而不是Vehicle。
关于c++ - 运算符(operator)问题<,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3759461/