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

来源:互联网 发布:java 统计学 mahout 编辑:程序博客网 时间:2024/06/06 15:47

复制代码

#include <iostream>using namespace std;int fuc(char *a){    cout << a << endl;}int main(){    fuc("hello");}
复制代码

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

问题是这样产生的,先看这个函数原型:

?
1
void someFunc(char *someStr);

再看这个函数调用:

?
1
someFunc("I'm a string!");

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

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

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

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
usingnamespace std;
int fuc(char *a)
{
cout << a << endl;
}
int fuc(const char *a)
{
cout << a << endl;
}
int main()
{
chara[] = "hello 123";
fuc(a);
constchar b[] = "hello 123";
fuc(b);
}
阅读全文
0 0