错误 C2679:二进制"=":未定义采用类型右侧操作数的运算符

error C2679: binary '=' : no operator defined which takes a right-hand operand of type

本文关键字:操作数 运算符 类型 二进制 C2679 未定义 错误      更新时间:2023-10-16

我需要你的帮助!这是我的代码:

strName = pWeapon->GetInvenNormalIcon();

strName 是一个字符串! 以及 GetInvenNormalIcon 的回归!但现在的问题来了!我需要在 char* var 上设置该字符串!我试着用这种方式去做

pWeapon->szName         = strName;

但是我得到那个错误

error C2679: binary '=' : no operator defined which takes a right-hand operand of type

我要做什么?谢谢

如果strName std::string则必须使用strName.c_str()方法来获取指向其内容的指针const char*。但是,您应该了解,如果strName是局部变量,它将在函数退出时释放,因此您的pWeapon->szName指针将变得悬空。也许最好也让它std::string

Upd:然而,就像@songyuanyao正确指出的那样,c_str()方法返回const char*,因此您不能直接使用它。应先分配内存,然后将字符串内容复制到其中。

pWeapon->szName = new char[strName.length() + 1];
strcpy_s(pWeapon->m_mData, strName.length()+1, strName.c_str());

您必须释放类析构函数中的pWeapon->szName,并确保在重新分配指针时内存不会泄漏。由于std::string会自动执行所有这些操作,因此最好使用它而不是指针。

相关文章: