您的位置:首页 > 其它

warning:deprecated conversion from string constant to 'char *' 解决方案2

2014-04-10 01:18 423 查看
#include <iostream>
using namespace std;

int fuc(char *a)
{
cout << a << endl;
}
int main()
{
fuc("hello");
}

Linux 环境下当GCC版本比较高时,编译代码可能出现以上题目中的问题。

问题是这样产生的,先看这个函数原型:
void someFunc(char *someStr);

再看这个函数调用:
someFunc("I'm a string!");

把这两个东西组合起来,用最新的g++编译一下就会得到标题中的警告。

为什么呢?原来char *背后的含义是:给我个字符串,我要修改它。

而理论上,我们传给函数的字面常量是没法被修改的。

所以说,比较和理的办法是把参数类型修改为const char *。

这个类型说背后的含义是:给我个字符串,我只要读取它。

如何同时接收const类型和非const类型?重载

#include <iostream>
using namespace std;

int fuc(char *a)
{
cout << a << endl;
}
int fuc(const char *a)
{
cout << a << endl;
}
int main()
{
char a[] = "hello 123";
fuc(a);
const char b[] = "hello 123";
fuc(a);这个的结果显示:
hello
123

hello
123

当你注释掉:

int fuc(const char *a)
{
cout << a << endl;
}错误如下:
hello1.c: In function ‘int main()’:
hello1.c:14:7: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
hello1.c:3:5: error: initializing argument 1 of ‘int fun(char*)’ [-fpermissive]
当你注释掉:
int fuc(char *a)
{
cout << a << endl;
}结果如下:
hello 123
hello 123
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐