I'm having trouble figuring out how to properly overload the '=' operator to assign one student's information to another's for one of my assignments. I'm new to this, so I could have messed it up big time. Thanks for any help!
#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(); }
classListanstd::vector<std::string>and you don't have to provide assignment operator, copy constructor, destructor, anything...