c++:warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

时间:2021-04-05 16:04:51

首先,它任然是有效的C++代码,应为你写的char* 是具有c风格的字符串,所以g++不识别

可以选择在编译的时候加上:g++ -Wno-write-strings text.cpp //忽略警告。。。

其实这样是并不是很安全

上代码

  1 #include <iostream>
  2 #include <stdio.h>
  3 #include <string.h>
  4 using namespace std;
  5 
  6 class Student{
  7   private:
  8     int score;
  9     char *name;//可变的变量
 10   public:
 11     Student(const char *name,int score);
 12     Student(Student& stu);
 13     ~Student();
 14     void  show();
 15 };
 16 
 17 Student::Student(const char *name1,int score1)//这里改了const
 18 {
 19   cout<<"constructing ..."<<endl;
 20 
 21   name = new char[strlen(name1)+1];
 22   if(name != 0)
 23   {
 24     strcpy(name,name1);
 25     score = score1;
 26   }
 27 }
 28 
 29 Student::~Student()
 30 {
 31   cout<<"Destructing..."<<endl;
 32   name[0] = '\0';
 33   delete name;
 34 }
 35 
 36 Student::Student(Student& stu)
 37 {
 38   cout<<"copy constructing ..."<<endl;
 39   name = new char[strlen(stu.name)+1];
 40   if(name != 0)
 41   {
 42     strcpy(name,stu.name);
 43 
 44     score=stu.score;
 45   }
 46 }
 47 
 48 void Student::show()
 49 {
 50   cout<<name<<endl;
 51   cout<<score<<endl;
 52 }
 53 
 54 int main()
 55 {
 56   Student stu1("huhao",101);//在这里传入的是const的变量
 57   /*
 58   Student stu2=stu1;
 59   stu1.show();
 60   stu2.show();*/
 61 }