warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

今天在linux下编译一个cpp文件时,报出了一个奇怪的错误:arning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

改了好一会也不知道哪出问题了,一度怀疑人生....

原来,当g++编译版本比较高是,linux下就会出现这样的问题。

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 struct person{
 5     int age;
 6     char *name;
 7 };
 8 int main(){
 9     int i = 0;
10     char *str = "aaaaaa";
11     person *p = NULL;
12     p->age = i;
13     p->name = str;
14     cout<<"his name is"<<*(p->name)<<", he is"<<p->age<<"years old"<<endl;
15     return 0;
16 }

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

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

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

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

所以,将char*使用const修饰就好了

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 struct person{
 5     int age;
 6     const char *name;
 7 };
 8 int main(){
 9     int i = 0;
10     const char *str = "aaaaaa";
11     person *p = NULL;
12     p->age = i;
13     p->name = str;
14     cout<<"his name is"<<*(p->name)<<", he is"<<p->age<<"years old"<<endl;
15     return 0;
16 }

还有一种方法,值得注意,就是g++编译的时候,传入-Wno-write-strings 可关闭该warning

posted @ 2019-03-16 21:26  leoncumt  阅读(6648)  评论(1编辑  收藏  举报