【问题标题】:C++ operator overload with pointer object带有指针对象的 C++ 运算符重载
【发布时间】: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


【解决方案1】:
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),这将按预期工作

【讨论】:

  • 谢谢你。我想我认为我需要指针,因为我在二进制搜索树中使用了这个 Entry 类。我认为我节点中的项目必须是一个指针。
  • @Christian4423 我知道老师会告诉你不然,但你真正需要指针的情况实际上非常罕见
猜你喜欢
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多