本文共 734 字,大约阅读时间需要 2 分钟。
deprecated conversion from string constant to ‘char*’
#includeusing 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> 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(b); } |
转载地址:http://qxgum.baihongyu.com/