【问题标题】:Adding two array objects with operator overloading resulting in segmentation fault添加两个具有运算符重载的数组对象导致分段错误
【发布时间】:2019-08-31 09:14:20
【问题描述】:

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

}

【问题讨论】:

  • 也就是说,如果你添加一个析构函数 deletes 是浮点数组,你肯定会因为缺少复制构造函数和 operator= 而遇到麻烦。
  • 你熟悉深拷贝和浅拷贝吗?
  • 这实际上是我所有的代码,它现在非常基本。我只注释掉了我正在处理的另一个运算符重载函数,但它与其余代码没有交互。另外我不知道深拷贝和浅拷贝是什么,我应该学习吗?

标签: c++ arrays pointers segmentation-fault operator-overloading


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    你没有初始化大小变量。

    你需要初始化它。

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

    而且你的 size 变量是私有的。

    所以,它不能引用。所以size变量需要声明为public。

    【讨论】:

    • @GirishTiwari 而且,您需要在析构函数中删除数组。有时我会很麻烦。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2014-11-30
    相关资源
    最近更新 更多