2014-04-03 144 views
0

我很難弄清楚如何正確地重載'='操作員以將一個學生的信息分配給另一個人的任務。我是新來的,所以我可以把它弄糟了。謝謝你的幫助!操作員超載故障

#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(); 
} 
+0

製作'classList'一個'標準::矢量'你不必提供賦值操作符,拷貝構造函數,析構函數,什麼... – juanchopanza

+0

你的類沒有一個用戶定義的析構函數清理內存,更不用說賦值運算符和複製構造函數了。 – PaulMcKenzie

回答

1

實現賦值運算符的正確方法是使用

Student& operator=(const Student& s){ 
    if (&s != this){ 
     this->name = s.name; 
     /*etc for all members*/ 
    } 
    return *this; 
} 

有幾件事情需要注意:

  1. s複製由恆定的參考通過。這意味着它不會進行深層複製,也不允許被該函數修改。

  2. 返回*this允許你做多項任務:a = b = c;

  3. if聲明避開與自我分配出現的任何問題。

  4. 要特別注意複製classList。確保進行深層複製。

這是迄今爲止最好使用標準模板庫的容器,所以你可以依靠編譯器生成的賦值運算符。

+1

classList是一個指針。它不應該被深拷貝? – fritzone

+0

@fritzone:可能;因此我對所有成員* /'相當模糊的'/ *等。但我覺得這是一個B型問題。讓我們先看看賦值運算符的形式。 – Bathsheba