我很難弄清楚如何正確地重載'='操作員以將一個學生的信息分配給另一個人的任務。我是新來的,所以我可以把它弄糟了。謝謝你的幫助!操作員超載故障
#include <iostream>
using namespace std;
class Student
{
public:
void input()
{
cout << "Please enter student's name: ";
cin >> name;
cout << "Please enter the number of classes " << name << " is taking: ";
cin >> numClasses;
classList = new string[numClasses];
cout << "Please enter the list of classes " << name << " is taking: ";
for(int i = 0; i < numClasses; i++)
{
cin >> classList[i];
}
}
void print()
{
cout << "Student's name: " << name << endl;
cout << "Number of classes " << name << " is taking: " << numClasses << endl;
cout << "List of classes " << name << " is taking: " << endl;
for(int i = 0; i < numClasses; i++)
{
cout << classList[i] << endl;
}
}
void resetClasses()
{
name.clear();
numClasses = 0;
delete [] classList;
}
Student operator= (Student s)
{
Student temp;
temp.name = s.name;
temp.numClasses = s.numClasses;
temp.classList = s.classList;
return temp;
}
private:
string name;
int numClasses;
string *classList;
};
int main()
{
Student s1, s2;
s1.input();
cout << "Student 1's data:" << endl;
s1.print();
s2 = s1;
cout << endl << "Student 2's data after assignment from student 1: " << endl;
s2.print();
s1.resetClasses();
cout << endl << "Student 1's data after reset:" << endl;
s1.print();
cout << endl << "Student 2's data, should still have original classes: " << endl;
s2.print();
}
製作'classList'一個'標準::矢量'你不必提供賦值操作符,拷貝構造函數,析構函數,什麼... –
juanchopanza
你的類沒有一個用戶定義的析構函數清理內存,更不用說賦值運算符和複製構造函數了。 – PaulMcKenzie