C++指针对象的运算符重载
C++ operator overload with pointer object
我正在努力将我的对象与另一个相同类型的对象进行比较。
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)
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板