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