c++ - 添加两个具有运算符重载的数组对象导致分段错误
问题描述
我在 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
将成员大小值设置为传递给构造函数的大小值。
当数组大小不同时,+ 运算符也不会注意离开数组。
推荐阅读
- javascript - @pnp/sp 确保适用于我的沙箱的工作台,但在部署时失败
- javascript - 如何使用照片 api 使用 vue 制作图像轮播
- android - 片段内的片段 {Kotlin}
- php - 如何在 Laravel 5.7 中翻译密码重置邮件?
- java - 自定义 listView 的问题 - 列表视图为空
- angular - Ngrx/ 影响在 SwitchMap 上传递空值
- .net - .Net 挂钩从 Powershell 中的路径获取文件夹名称
- php - AADSTS50011 请求中指定的回复 uri 未使用安全方案。基于 REST 的 PHP
- reactjs - c3js:如何在不是x轴类别之一的垂直条形图中添加垂直线?
- c# - 如何在使用 C# 中的 Dapper 插入之前检查 mysql 数据库中是否已存在具有复合键的记录