C++指针对象的运算符重载

C++ operator overload with pointer object

本文关键字:运算符 重载 对象 指针 C++      更新时间:2023-10-16

我正在努力将我的对象与另一个相同类型的对象进行比较。

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"

我能让它工作的唯一方法是将条目声明为对象而不是指针。

我以为这个问题会是一个快速搜索,但我无法找到重复的。让我知道以前是否问过这个问题。

如何比较这两个指针?

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;

这总是错误的。

它总是false,因为你在比较两个不同对象的地址。实际上,一般来说,除非你对指针进行推导,否则你对指针无能为力。如果要调用Entry::operator==则需要取消引用指针,如下所示:

bool isSame = *name == *name2;

顺便说一句,问题出现了,你为什么首先使用指针?只需使用普通对象,您的问题就消失了:

auto name =  Entry<string, string>(names[9], paths[9]);
auto name2 = Entry<string, string>(names[9], paths[9]);
bool isSame = name == name2;

这将按预期工作,前提是您提供Entry::operator==(Entry)