You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++指针对象==运算符重载问题:同类型对象比较始终返回false

问题分析与解决方案

你遇到的问题核心在于指针地址比较 vs 对象内容比较,以及运算符重载的参数设计错误,下面一步步拆解解决:

1. 为什么name == name2永远返回false?

name和name2是两个Entry<string, string>*类型的指针,直接用==比较时,C++默认比较的是指针存储的内存地址——你用new创建了两个独立的对象,它们的内存地址肯定不同,所以结果必然是false,和对象内容无关。

2. 修正==运算符重载的参数设计

你当前的重载函数参数是指针类型,这不符合C++运算符重载的常规设计(而且这种重载几乎不会被调用到,因为指针的==是内置操作)。正确的做法是将重载的参数改为const引用,这样才能比较两个对象的内容:

template<class KeyType, class ItemType>
class Entry {
private:
    KeyType key;
    ItemType item;
public:
    // 构造函数
    Entry(const KeyType& k, const ItemType& i) : key(k), item(i) {}

    // 重载==运算符,参数为const引用(保证不修改右值,同时避免拷贝)
    bool operator==(const Entry<KeyType, ItemType>& right) const {
        // 比较对象的核心成员,这里假设Entry有key和item两个成员
        return (key == right.key) && (item == right.item);
    }
};

3. 正确调用重载的==运算符

既然我们重载的是对象之间的==,那么需要对指针解引用,获取指针指向的对象后再比较:

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; // 现在会返回true

额外建议

如果可以的话,尽量避免使用裸指针管理内存,推荐使用智能指针(比如std::unique_ptr或std::shared_ptr),这样能避免内存泄漏问题:

#include <memory>

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

内容的提问来源于stack exchange,提问作者Christian4423

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:27:14