如果我们需要解决警告,最好的解决方案是什么:
代码如下所示:
#include<iostream>
using namespace std;
int main()
{
// There is a call to the function myfunc
myfunc(char*, char*, char*, int, char*, char*, char*, char*, char*,
char*, char*, char*, char*, char*, char*,
char*, char*, int, int, int, int, int,
int, int, int, int, int, int, int,
int, int,int,int=9999,int=11,int=8888,char* ="",char* ="");
return 0;
}
Warning: String literal converted to char* in initialization.
在这里,我面临的问题是 - 我认为最后两个字符 * ="。此外,由于某些默认参数是在 之间指定的,因此必须用双引号指定最后两个 char*。请让我知道如何摆脱警告消息。
您正在使用字符串文字(即 const)作为非常量参数,可以在函数中修改。这是危险的,因为这(通常)是只读内存。编译器会警告您这一事实。
如果需要修改字符串,要么删除默认参数,要么使用 std::string
并像这样定义它们:
std::string = std::string()
不过,您似乎有很多或函数参数,也许class
或struct
在这里可能是有益的。然后使用 std::string 实现最后 2 个参数几乎是微不足道的,因为无论如何您都需要重构调用该函数的所有代码。
编辑
假设myfunc
是这样定义的(我;)删除了一些参数),并使用一些内部函数仅读取然后可能修改最后一个参数。
void myfunc(char* first, std::string second = std::string())
{
// read_only_function takes a const char*
read_only_function(second.c_str());
// modify_function takes a char*, it should probably take a length too
// or have some kind of documented agreement on length.
char temp[choose_your_size];
modify_function(temp, ... and possibly buffer size);
second.assign(temp, ...); // Pick the according overloads
}
当然,这只是在您无法控制这些内部功能的情况下。如果你有,我也会重构它们以在参数中获取 std::string 进行修改。
最后,请记住,std::string
不一定包含以 null 结尾的字符串,因此在使用 c_str
时要小心。
将最后两个参数更改为 const char *
或更好的是,std::string
。
您还可以让它们默认为 NULL
并对函数进行编码以处理这种情况,就像传递空字符串一样。