zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    线程
    简单排序
    SSM的整合
    SpringMVC中的拦截器、异常处理器
    SpringMVC的文件上传
    SpringMVC的数据响应和结果视图
    springMVC的常用注解
    SpringMVC入门
    Spring中声明式事务控制
    JdbcTemplate在spring中的使用
  • 原文地址:https://www.cnblogs.com/leoncumt/p/10544416.html
Copyright © 2011-2022 走看看