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

首先,它任然是有效的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 }


  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值