添加两个具有运算符重载的数组对象,从而导致分段错误
Adding two array objects with operator overloading resulting in segmentation fault
我正在用 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];
}
您的大小变量是私有的。
所以,它不能引用。所以大小变量需要声明为公共。
相关文章:
- 将对象数组的引用传递给函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 类对象数组的问题会导致崩溃
- Arduino C++在构造函数中用参数声明对象数组
- 使用对象数组对 SFML 进行动画处理
- C++ 对象数组堆栈溢出
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何初始化对象数组?
- C++创建对象数组
- 在对象数组中搜索字符串并返回相应值的函数
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 使用 C++ 创建对象数组
- 对象数组打印空白字符串
- 重载运算符 [] 用于从对象数组中给出特定索引
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组