XCode下JSON解析库JSONObject赋值字符串误调用bool重载operator=问题
解决JSONObject字符串赋值匹配到bool运算符的问题
嘿,这个问题我之前写自定义数据类型的时候也踩过坑!核心原因是C++的类型转换优先级规则在作祟,咱们一步步拆解清楚:
问题根源
你执行nItem = "My New Item";时,"My New Item"是const char*类型的字符串字面量,但你的JSONObject类里并没有直接重载operator=(const char*)。这时候编译器会自动寻找“可行的隐式转换路径”:
- 要匹配
operator=(std::string),需要把const char*调用std::string的构造函数做一次用户定义的转换; - 而
const char*可以直接隐式转换成bool(非空指针会被转成true),这是内置的隐式转换,优先级比用户定义转换更高。
所以编译器自然就选了operator=(bool),而不是你期望的std::string版本。
修复方案
最简单直接的办法就是添加const char*版本的赋值运算符重载,让字符串字面量能直接匹配到正确的重载:
class JSONObject { //... public: // 保留你原来的所有重载 void operator=(int); void operator=(long); void operator=(float); void operator=(double); void operator=(bool); void operator=(std::string); // 添加这个重载 void operator=(const char* str) { // 直接复用现有的std::string重载逻辑,避免重复代码 *this = std::string(str); } //... };
这样一来,当你再写nItem = "My New Item";时,编译器会优先匹配operator=(const char*),然后内部转成std::string处理,完美解决匹配错误的问题。
另外还有个小优化建议:把operator=(std::string)改成operator=(const std::string&),这样可以避免不必要的字符串拷贝,提升效率:
void operator=(const std::string& str) { // 你的逻辑实现 }
内容的提问来源于stack exchange,提问作者Jorge Omar Medra
相关产品推荐
相关产品推荐

