复制分配运算符错误
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初始化为任何内容,因此courses[k]可以是对任何位置的引用。基本类型不是在c++中默认初始化的。
相关文章:
- 在运算符重载定义中使用成员函数(const错误)
- 逻辑运算符上出现错误代码 a')'
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++:需要帮助了解运算符重载错误
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- C++分数混合比较运算符错误
- 为什么我收到错误:"运算符<<不匹配?
- 迭代器类的重载前缀增量运算符会引发分段错误
- 在 boost::qi 中使用过多的替代运算符会导致分段错误
- 调用运算符时出现链接器错误<<,如何解决?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 解决错误:运算符 [] 不匹配
- 提升错误:"运算符=="的重载不明确
- 字符串输入中没有匹配的错误运算符错误
- 错误:运算符 = IN C++ 不匹配
- QT 创建器错误(运算符 + 不匹配)
- 错误C++运算符重载
- 错误:运算符==不匹配
- C++ 语法和编译器错误 - 运算符不匹配<<
- C++错误--运算符=不匹配