c++ - 运算符重载麻烦

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

最佳答案

实现赋值运算符的正确方法是使用

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

一些注意事项:

  1. 要复制的s常量引用 传递。这意味着它不需要深拷贝,也不允许被函数修改。

  2. Return *this 允许你做多重赋值:a = b = c;

  3. if 语句避免了自赋值引起的任何问题。

  4. 特别注意classList的复制。确保进行深拷贝。

但是 使用标准模板库容器要好得多,这样您就可以依赖编译器生成的赋值运算符。

关于c++ - 运算符重载麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22846713/

相关文章:

c++ - 如何传输模板?

c++ - 如何在另一个类中使用结构定义

c++ - 表达式 : Invalid Operator < - Can't find the error

C++ 重载 = 运算符

C++ std::list 排序保留顺序

c++ - 在 CRichEditCtrl 上使用表情符号时内存泄漏

c++ - cpp 文件中具有简单定义的虚函数导致链接器错误

python - 如何在 Python 中模拟赋值运算符重载?

c++ - 在类外重载运算符

ios - swift 中的后缀递归自定义运算符