不推荐从字符串常量转换为char*错误
Deprecated conversion from string constant to char * error
可能重复:
C++不赞成从字符串常量转换为"char*">
我有以下代码,虽然我没有复制完整的代码,因为它是巨大的。以下代码在template类中,我收到如下警告。由于模板中的警告,我无法实例化它,并出现"从这里实例化"错误。
警告:不赞成从字符串常量转换为"char*">
void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, char* pcMessage, char* pcFileName, unsigned int RowNo)
{
//...
}
char cCompleteMessage[200];
memset(cCompleteMessage, 0x00, sizeof(cCompleteMessage));
char*cMessage = "add reorgenize failed";
ErrorMessageInRaphsodyCode(cCompleteMessage, cMessage, "omcollec.h", __LINE__);
我的问题是,消除上述警告的最佳方法是什么?
如果函数采用char const *
,它保证只读取指针指向的任何数据。但是,如果它采用像char *
这样的非常量指针,它可能会向其写入。
由于写入字符串文字是不合法的,编译器将发出警告。
最好的解决方案是将函数更改为接受char const *
而不是char *
。
char cMessage[] = "add reorganize failed";
这应该可以消除警告。
最好的方法是修复接受参数的函数。
如果您的代码是正确的,并且函数确实使用字符串常量,那么它应该在其原型中这样说:
void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, char* pcMessage, const char* pcFileName, unsigned int RowNo)
如果你不能做到这一点(你没有代码(,你可以创建一个内联包装器:
inline void ErrorMessageInRaphsodyCodeX(char* p1, char* p2, const char* p3, unsigned int p4)
{ ErrorMessageInRaphsodyCode(p1,p2,(char*)p3,p4); }
并使用包装器。
如果您的代码不正确,并且函数确实需要可写内存(我对此深表怀疑(,则需要按照Jan的建议创建一个本地数组,或者malloc
提供足够的内存,从而使字符串可写。
(1(使变量成为const char*
(..., const char* pcFileName, ...)
(2(如果以上不可能,并且您希望保留char*
和const char*
的状态,则将函数设为template
:
template<typename CHAR_TYPE> // <--- accepts 'char*' or 'const char*'
void ErrorMessageInRaphsodyCode(char* pcCompleteMessage, CHAR_TYPE* pcMessage, char* pcFileName, unsigned int RowNo)
{
//...
}
函数std::string
类的c_str()
。
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- strncpy之后的char数组的错误行为
- C++错误:初始值设定项过多,无法'char[26]'
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 使用 char* 存储数据和产生的错误
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- C++错误:无法将参数 2 从 'char' 隐蔽到 char[]'
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 使用外部变量会导致"unsigned char"错误LNK2001
- 如何修复C++中的'cannot convert char to char*'错误?
- 转换LPVOID IN CHAR错误C2440:=
- 将字符串传递给函数时出现"conversion to const char*"错误
- 创建新文件时std::string to const char*错误
- Fopen在c++中获取char *错误
- c++将整数复制到char[]或unsigned char[]错误
- 从"const char*"到"char"错误的无效转换
- 不推荐从字符串常量转换为char*错误
- 将所有nsdata字节复制到char*错误中
- 初始化"int strcmpi(const char*, const char*)"错误的参数 1