为什么这段代码会产生错误?
Why does this code generate error?
我有一个类,它包含另一个名为Sphere的类的数组。现在我不确定为什么一部分代码会产生错误。
. h文件sphere* list;
int listlen;
void add(sphere x);
sarray operator +(const sarray& arrayone);
. cpp
sarray::sarray()
{
listlen = 0;
list = new sphere[200000];
}
sarray::~sarray()
{
delete [] this->list;
}
void sarray::add(sphere x) // Function for adding spheres to the list.
{
listlen++;
list[listlen-1] = x;
}
void sarray::operator = (const sarray& arrayone)
{
this -> list = NULL;
for(int i = 0; i < arrayone.listlen; i++)
{
this -> add(arrayone.list[i]);
}
}
sarray sarray::operator +(const sarray& arrayone)
{
sarray temparray;
for(int i = 0; i < arrayone.listlen; i++) // add all the elements from the first array to the temporary one
{
//sphere temp = arrayone.list[i];
temparray.add(arrayone.list[i]);
}
for(int j = 0; j < this -> listlen; j++)// add all the elements from the second array to the temporary one
{
temparray.add(list[j]);
}
return temparray;
}
球体类有一个成员变量叫做"Radius"当我尝试像这样比较
float a = 10;
for(int i=0; i > this->listlen;i++)
if(this->list[i].Radius > a) //<-- Can read the values
可以正常工作,但是当更改这部分代码时
float a = 10;
sarray temparray = arrayone + *this;
for(int i = 0; i < temparray.listlen; i++)
if(temparray.list[i].radius > a) // Error comes here!
"Unhandled exception at 0x00138503: Access violation reading location"
,而这没有。我猜问题是在添加/操作符功能,但我找不到它。
以下部分看起来有问题:
void sarray::add(sphere x) // Function for adding spheres to the list.
{
list[listlen-1] = x;
}
你应该有这样的东西
void sarray::add(sphere x) // Function for adding spheres to the list.
{
list[listlen++] = x;
}
看了析构函数,你在数组中有一个指向sphere的指针,并且有一个析构函数来销毁该指针。除了没有定义自己的复制构造函数之外,这一切都很好,这意味着使用默认的复制构造函数。在返回temparray的函数操作符+中,将返回本地副本的副本。调用默认的复制构造函数来创建副本。然后本地的会被销毁。现在返回的数组副本的列表将指向无效数据。您需要定义自己的复制构造函数来对列表指针进行深度复制。
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 为什么我在使用void函数时得到错误代码C2276
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 逻辑运算符上出现错误代码 a')'
- 'val' Arduino 错误代码之前的预期'('
- 我在贪吃蛇游戏中收到了错误代码 -1073741571
- 根据 GetLastError 直接写入磁盘会导致错误代码 5
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- 创建进程 API 失败,在窗口 122 上出现错误代码 10
- 使用另一个函数调用一个函数(都在类中)时出现问题.没有错误代码C++
- 当命令失败时,gzip 会在 C++ 中返回错误代码吗?
- 从 C++ 调用 cURL 命令会返回意外的错误代码,如 1792 和 6656
- WSALookupServiceBegin() 上的错误代码 10022(无效的 arugment)
- C++ Schannel POST 400 错误代码错误请求
- openCL-创建子缓冲区返回错误代码13
- 更新了Runge-Kutta(RK4)C++错误代码中的二阶DE
- 获取有关使用未初始化内存的错误代码
- 排序程序的意外错误代码
- 正在将DJI错误代码记录到流中
- 来自API的错误代码..处理什么是好的做法