warning: deprecated conversion from string constant to 'char*
#include<iostream> using namespace std; class Student { private: int age; char*name; public: Student(int m, char *n) { age=m;name=n; } Student() { age=0;name="unnamed"; } ~ Student(){} void SetMember ( int m,char *n ) { age=m;name=n; } int Getage(){return age;} char *Getname(){return name;} }; int main() { Student stu[3]={Student(13,"wang"),Student(),Student()} ; stu[2].SetMember(12,"zhang"); cout<<stu[0].Getage()<<","<<stu[0].Getname()<<endl; cout<<stu[1].Getage()<<","<<stu[1].Getname()<<endl; cout<<stu[2].Getage()<<","<<stu[2].Getname()<<endl; return 0; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#include<iostream> using namespace std; class Student { private : int age; const char *name; public : Student( int m, const char *n) { age=m; name=n; } Student() { age=0; name= "unnamed" ; } ~ Student() {} void SetMember ( int m, const char *n ) { age=m; name=n; } int Getage() { return age; } const char *Getname() { return name; } }; int main() { Student stu[3]= {Student(13, "wang" ),Student(),Student()} ; stu[2].SetMember(12, "zhang" ); cout<<stu[0].Getage()<< "," <<stu[0].Getname()<<endl; cout<<stu[1].Getage()<< "," <<stu[1].Getname()<<endl; cout<<stu[2].Getage()<< "," <<stu[2].Getname()<<endl; return 0; } |
看你的实现,传给Student类的字符串都是不可变的,都加上const就好了;否则你就要复制一份并且自己管理那块内存了。