繁体   English   中英

复印分配操作员错误

[英]Copy assignment operator error

我正在尝试制作副本分配运算符。 但这是行不通的。 问题是什么? 还有其他写副本分配运算符的方法吗?

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;
    }
 }

我应该做些什么?

您无需将k初始化为任何东西,因此Course [k]可以是对任何地方的引用。 基本类型不是在c ++中默认初始化的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM