我有一个程序,使用一个类来动态分配数组。我重载了运算符来对该类的对象进行操作。
当我测试这个程序时,重载的 += 运算符可以正常工作,但 -= 却无法工作。当尝试运行重载的 -= 时,程序崩溃并出现以下运行时错误:
malloc:*错误对象为0x7fd388500000:释放的指针未被分配*请在malloc_error_break中设置断点以进行调试。
在私有成员变量中,我像这样声明数组:
我有以下两个重载构造函数,作为Students类的友元函数定义:
这些定义如下:
基本上这里发生的事情是,我正在比较两个根据 classL 大小不同的数组对象。getClassL() 函数仅为:int Student::getClassL() const {return classLists;}。
如果你想知道,我已经按照以下方式重载了三个重要函数:
1. 析构函数:Student::~Student() {delete [] array_d;}
2. 拷贝构造函数:
当我测试这个程序时,重载的 += 运算符可以正常工作,但 -= 却无法工作。当尝试运行重载的 -= 时,程序崩溃并出现以下运行时错误:
malloc:*错误对象为0x7fd388500000:释放的指针未被分配*请在malloc_error_break中设置断点以进行调试。
在私有成员变量中,我像这样声明数组:
double* array_d;
然后我在重载的构造函数中动态分配数组:
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);
}
}
基本上这里发生的事情是,我正在比较两个根据 classL 大小不同的数组对象。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;
}
+= 可以使用,但 -= 不起作用,这很奇怪,因为它们实际上是相同的操作。我怀疑问题出在动态内存分配上,但我不确定,正在寻求专家的建议。
operator +=
和-=
应该返回当前对象的引用,而不是一个新的对象。因此,你的代码针对+=
和-=
需要两个Student
对象没有太多意义。这些函数应该通过引用接收单个Student
对象并将其添加到this
,然后返回*this
。如果它们是+
和-
运算符,那么带两个参数的函数会更有意义一些。 - PaulMcKenzie