添加两个具有运算符重载的数组对象,从而导致分段错误

Adding two array objects with operator overloading resulting in segmentation fault

本文关键字:对象 数组 错误 分段 重载 两个 运算符 添加      更新时间:2023-10-16

我正在用 c++ 设置一个类,该类将具有数组对象和一个将它们添加在一起的函数(通过添加它们的各个组件(。这些对象中的每一个都有一个指向将加在一起的浮点数的"新"数组的指针。我相信,无论是因为这些是指针还是分配给"新"数组,通过重载 + 运算符访问它们的组件时存在某种内存问题,但我不确定具体是什么问题。该文件编译没有任何问题,但在运行时只是说"分段错误(核心转储("。我也知道我应该在 for 循环中使用最小值而不是最大值,但现在我所有的数组大小都相同,所以我只是以这种方式测试它。

如果我注释掉 main(( 中数组的实际添加,错误消息会完全消失,但我不太确定为什么。

#include  <iostream>
using namespace std;
class Array
{
private:
   int size, location;
   float value;
public:
   float *arrayptr;
Array(int size)
{
   arrayptr = new float[size];
}
void setValue(int location, float value)
{
   arrayptr[location] = value;
}
Array operator+(Array a)
{
   int max;
   if (a.size >= size)
   {
      max = a.size;
   }
   else
   {
      max = size;
   }
   Array tmparray(max);
   for(int i=0; i<max; i++)
   {
      tmparray.arrayptr[i] = a.arrayptr[i] + arrayptr[i];
   }
   return tmparray;
}
};
main()
{
   Array a1(3);
   a1.setValue(0, 1.0);
   a1.setValue(1, 22.0);
   a1.setValue(2, 12.2);
   Array a2(3);
   a2.setValue(0, 3.3);
   a2.setValue(1, 44.5);
   a2.setValue(2, 21.7);
   Array tmp(3);
   // Source of the error (parenthesis doesn't seem to affect it):
   tmp = (a1 + a2);
}

您不会在构造函数中设置大小,因此当if (a.size >= size)发生时,您将获得未定义的行为。可能会被设置为一些荒谬的值,然后您离开数组。

m_size = size 将成员大小值设置为传递到构造函数的大小值。

当数组大小不同时,+ 运算符也不会注意离开数组。

您尚未初始化大小变量。

您需要初始化它。

Array(int _size)
{
    size = _size;
    arrayptr = new float[size];
}

您的大小变量是私有的。

所以,它不能引用。所以大小变量需要声明为公共。