我在使用指针使用动态字符串数组的程序时遇到问题。在我完成在函数 courseLoad 中打印出数组的元素后,我收到了 Segmentation Fault(Core Dumped) 错误。这是我的代码:
5 #include<iostream>
6 #include<cstdlib>
8
9 using namespace std;
10
11 class Student
12 {
13 public:
14 string name;
15 int numClasses;
16 string* classList;
17
18 Student() {};
19 Student(string, int, string*);
20 ~Student() {delete[] classList;};
21
22 string getName();
23 void setName();
24 int getNumClasses();
25 void setNumClasses();
26 string* getClassList();
27 void setClassList();
28
29 void inputs();
30 void courseLoad();
31 void emptyClasses();
32
33 Student operator=(const Student& other);
34
35 };
36
37 Student::Student(string name, int numClasses, string* classList)
38 {
39 this->name = name;
40 this->numClasses = numClasses;
41 classList = new std::string[100] ();
42 }
43
44 string Student::getName()
45 {
46 return name;
47 }
48
49 void Student::setName()
50 {
51 cout << "Please type the name of the student: ";
52 cin >> name;
53 }
54
55 int Student::getNumClasses()
56 {
57 return numClasses;
58 }
59
60 void Student::setNumClasses()
61 {
62 cout << "Please enter the amount of classes this student is taking: ";
63 cin >> numClasses;
64 }
65
66 string* Student::getClassList()
67 {
68 return classList;
69 }
70
71 void Student::setClassList()
72 {
73 cout << "Please enter the classes that this student is taking: ";
74 for(int i = 0; i < numClasses; i++)
75 {
76 getline(cin, classList[i]);
77 }
78 }
79
80 void Student::inputs()
81 {
82 string word;
83 classList = new string[100];
84
85 cout << "Please enter the name of the student: ";
86 getline(cin, name);
87 cout << "Please enter the number of classes that " << name << " is taking: ";
88 cin >> numClasses;
89 cin.ignore();
90
91 cout << "Please enter the names of the classes " << name << " is taking: ";
92 for(int i = 0; i < numClasses; i++)
93 {
94 getline(cin, word);
95 classList[i] = word;
96 }
97 }
98
99 void Student::courseLoad()
100 {
101 cout << name << endl;
102 cout << "===============================" << endl;
103 for(int i = 0; i < numClasses; i++)
104 {
105 cout << classList[i];
106 cout << "\n";
107 }
108 }
109
110 void Student:: emptyClasses()
111 {
112 numClasses = 0;
113 for(int i = 0; i < numClasses; i++)
114 {
115 classList[i] = "";
116 }
117 }
118
119 Student Student::operator=(const Student& other)
120 {
121 Student temp;
122 return (temp);
123 }
124
125 int main()
126 {
127 Student s1, s2;
128
129 s1.inputs();
130 cout << "Student 1's Data: ";
131 s1.courseLoad();
132 cout << "Hello";
133
134 s2 = s1;
135 cout << "Student 2's data after assignment from student 1: " << endl;
136 s2.courseLoad();
137
138 s1.emptyClasses();
139 cout << "Student 1's data after reset: " << endl;
140 s1.courseLoad();
141
142 cout << "Student 2's data, should still have original classes: " << endl;
143 s2.courseLoad();
144
145 return 0;
146 }