操作员超载故障

时间:2014-04-03 19:07:00

标签: c++ operator-overloading

我无法确定如何正确地超载' ='操作员将一个学生的信息分配给另一个学生的作业。我对此很陌生,所以我可能把它搞砸了。谢谢你的帮助!

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

1 个答案:

答案 0 :(得分: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的复制。确保获得深层复制。

  5. 使用标准模板库容器要好得多,因此您可以依赖编译器生成的赋值运算符。