I have a program that uses a class to dynamically allocate an array. I overloaded operators that perform operations on objects of this class.
When I test this program, overloaded + = works, but - = does not work. When the program crashes when I try to start the overloaded - =, I get the following runtime error:
malloc: * error for object 0x7fd388500000: no pointer was freed> highlighted * set breakpoint in malloc_error_break for debugging
In private member variables, I declare an array as follows:
double* array_d;
Then I dynamically allocate the array in the overloaded constructor:
Students::Students(int classLists)
{
classL = classLists;
array_d = new double[classL];
}
, Students:
friend Student operator+= (const Student&, const Student&);
friend Student operator-= (const Student&, const Student&);
:
Student operator+= (const Student& stu1, const Student& stu2)
{
if (stu1.getClassL() >= stu2.getClassL())
{
for (int count = 0; count < stu.getClassL(); count++)
stu1.array_d[count] += stu2.array_d[count];
return (stu1);
}
else if (stu1.getClassL() < stu2.getClassL())
{
for (int count = 0; count < stu1.getClassL(); count++)
stu1.array_d[count] += stu2.array_d[count];
return (stu1);
}
}
Student operator-= (const Student& stu1, const Student& stu2)
{
if (stu1.getClassL() >= stu2.getClassL())
{
for (int count = 0; count < stu2.getClassL(); count++)
stu1.array_d[count] -= stu2.array_d[count];
return (stu1);
}
else if (stu1.getClassL() < stu2.getClassL())
{
for (int count = 0; count < stu1.getClassL(); count++)
stu1.array_d[count] -= stu2.array_d[count];
return (stu1);
}
}
, , , L. getClassL() : int Student::getClassL() const {return classLists;}
, , :
1. : Student::~Student() {delete [] array_d;}
2. :
Student::Student(const Student &student)
{
classLists = student.classLists;
array_d = student.array_d;
}
3. :
Student &Student::operator=(const Student &student)
{
classLists = student.classLists;
array_d = student.array_d;
}
, + = , - = , . , , .