C++中如何在if语句中比较string*与const char*类型的值
报错原因
- 直接报错根因:
HashNode类的word成员是std::string*指针类型,你代码中写的table[slot]->word == word是拿指针的内存地址和std::string对象做相等判断,二者类型完全不匹配,编译器无法处理所以抛出该错误。 - 隐藏的严重问题1:构造函数中
this->word = &word;取的是构造函数形参word的地址,这个形参是函数局部变量,构造函数执行完成后就会被系统回收,后续访问word指针属于访问野指针,会出现不可预期的运行时崩溃。 - 隐藏的严重问题2:你修改
status为const char*类型后,构造函数直接给this->status赋值形参status(std::string类型)的底层指针,同样会因为形参销毁变成野指针,后续对比status的值也会出问题。
修复方案
方案1:移除没必要的指针定义(最推荐)
std::string本身已经做了内存管理,没必要额外存储指针,直接存值即可,还能避免野指针、内存泄漏问题:
class HashNode{ public: std::string word; std::string status; // 也可以定义枚举类型替代字符串,避免拼写错误问题 HashNode(std::string word, std::string status) { this->word = std::move(word); this->status = std::move(status); } };
修改完成后你原有逻辑代码不需要做任何调整,即可正常运行。
方案2:保留指针写法的修复方式(不推荐,需要自行管理内存)
如果你因特殊需求必须保留指针定义,需要修改两个位置:
- 修正HashNode构造函数,给
word在堆上申请内存,避免野指针,同时添加析构函数释放内存:
class HashNode{ public: std::string *word; const char *status; HashNode(std::string word, const char* status) { // 在堆上新建string对象,生命周期和HashNode绑定 this->word = new std::string(std::move(word)); // 此处要求传入的status必须是字符串常量(比如"never used"),否则需要额外做内存拷贝 this->status = status; } // 补充析构函数释放内存,避免泄漏 ~HashNode() { delete word; } // 注意:还需要自行实现拷贝构造、拷贝赋值、移动构造、移动赋值函数,避免double free问题,此处省略 };
- 对比
word的值时,先解引用指针拿到std::string对象再做判断:
while (table[slot]->status != "never used"){ // 加*解引用指针 if(*(table[slot]->word) == word) return true ; slot = (slot + 1) % TableSlots ; }
内容的提问来源于stack exchange,提问作者melarnmurphy
相关产品推荐
相关产品推荐

