【发布时间】:2018-10-12 21:08:50
【问题描述】:
我正在将我的对象与另一个相同类型的对象进行比较。
Entry<string, string>* name = new Entry<string, string>(names[9], paths[9]);
Entry<string, string>* name2 = new Entry<string, string>(names[9], paths[9]);
bool isSame = name == name2;
这总是错误的。
在我的实现中,我尝试了一些事情,但没有运气。
template<class KeyType, class ItemType>
bool Entry<KeyType, ItemType>::operator==(Entry<KeyType, ItemType>* rightHandItem)
{
KeyType key = rightHandItem->getKey();
return (searchKey == key);
}
template<class KeyType, class ItemType>
bool Entry<KeyType, ItemType>::operator>(Entry<KeyType, ItemType>* rightHandItem)
{
KeyType key = rightHandItem->getKey();
return (searchKey > key);
}
template<class KeyType, class ItemType>
bool Entry<KeyType, ItemType>::operator<(Entry<KeyType, ItemType>* rightHandItem)
{
KeyType key = rightHandItem->getKey();
return (searchKey < key);
}
这是我的类头文件
#pragma once
template<class KeyType, class ItemType>
class Entry
{
public:
Entry();
Entry(KeyType& searchKey);
Entry(KeyType& searchKey, ItemType newEntry);
~Entry();
ItemType getItem() const;
KeyType getKey() const;
void setItem(const ItemType& newEntry);
bool operator==(const Entry<KeyType, ItemType>& rightHandItem) const;
bool operator>(const Entry<KeyType, ItemType>& rightHandItem) const;
bool operator<(const Entry<KeyType, ItemType>& rightHandItem) const;
bool operator==(Entry<KeyType, ItemType>* rightHandItem);
bool operator>(Entry<KeyType, ItemType>* rightHandItem);
bool operator<(Entry<KeyType, ItemType>* rightHandItem);
private:
ItemType Item;
KeyType searchKey;
protected:
void setKey(const KeyType& searchKey);
};
#include "Entry.cpp"
我可以让它工作的唯一方法是如果我将条目声明为对象而不是指针。
我认为这个问题会是一个快速搜索,但我一直找不到重复项。让我知道以前是否有人问过这个问题。
如何比较两个指针?
【问题讨论】:
-
您不能为指针重载运算符(作为 rhs)。你不能简单地比较实例而不是指针吗?
-
“这总是错误的。” - 因为它正在比较指针。为什么需要用
new分配这些东西? -
为什么你首先使用指针?这是什么原因?您没有任何虚函数或继承,因此不涉及需要指针的多态性。并且通过正确的rule of three/five/zero 坚持,你真的不需要那么多指针。
-
至于无论如何用指针解决它(尽管我强烈推荐 against 它),请考虑取消引用运算符。
-
我会尝试解决这些问题。如果不需要,我会删除它们。
标签: c++ pointers operator-overloading