首页 > 解决方案 > 添加两个具有运算符重载的数组对象导致分段错误

问题描述

我在 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);

}

标签: c++arrayspointerssegmentation-faultoperator-overloading

解决方案


你没有在构造函数中设置大小,所以当if (a.size >= size)发生时,你会得到未定义的行为。可能会设置为一些可笑的值,然后您就离开了数组。

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

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


推荐阅读