【问题标题】:Copy assignment operator error复制赋值运算符错误
【发布时间】:2013-12-04 22:32:13
【问题描述】:

我正在尝试制作一个复制赋值运算符。但它不起作用。问题是什么? 有没有其他写复制赋值运算符的方法?

Course&  Course::operator= ( const Course &that)
{
    if (this != &that)
    {
        courseId = that.courseId; // in this line I'm getting run-time error.
        courseName = that.courseName;
        gradeFormLength = that.gradeFormLength;
        studentsLength = that.studentsLength;

        delete[] gradeForms;
        gradeForms = new GradeForm[that.gradeFormLength];
        for(int i = 0; i < that.gradeFormLength; i++)
        {
            gradeForms[i] = that.gradeForms[i];
        }

        delete[] students;
        students = new Student[studentsLength];

        for(int i = 0; i < that.studentsLength; i++)
        {
            students[i] = that.students[i];
        }
    }
    return *this;
}

这是调用 = 运算符的地方。

void StudentReviewSystem::deleteCourse(const int courseId)
{
    int index = findCourse(courseId);

    if(index != -1)
    {
        int newNum = numberOfCourses-1;
        Course *newCourses = new Course[newNum];
        int k;
        for(int j = 0; j < newNum; j++)
        {
            if(courses[j].getId() == courseId)
                k++;
            newCourses[j] = courses[k]; // <<< there
            k++;
        }
        delete[] courses;
        courses = newCourses;
        numberOfCourses = newNum;
        cout<< "Course "<< courseId <<" has been deleted."<< endl;
    }

    else
    {
        cout<< "Course "<< courseId <<" doesn't exist."<< endl;
    }
 }

我该怎么办?

【问题讨论】:

  • 您必须先定义“不起作用”。然后提供一个演示/重现问题的最小工作示例。
  • 首先,它不为空。其次,程序在执行该行时会崩溃。

标签: c++ copy variable-assignment operator-keyword


【解决方案1】:

您不会将 k 初始化为任何内容,因此 course[k] 可以是对任何地方的引用。基本类型在 c++ 中不是默认初始化的。

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 2017-11-21
    • 2012-03-01
    • 2011-11-16
    • 2020-02-28
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多