[英]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;
}
sphere类有一个名为“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"
虽然这样做了。 我想问题是在Add / operator函数中,但我找不到它。
以下部分看起来有问题:
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;
}
另外,您最好在add方法中进行一些错误检查。
好的,看过析构函数,你在sarray中有一个指向sphere的指针,并有一个析构函数来销毁指针。 除非您没有定义自己的复制构造函数,这意味着使用了默认的复制构造函数,否则这一切都很好。 在返回temparray的函数operator +中,返回本地副本的副本。 调用默认的复制构造函数来创建副本。 然后当地人将被毁坏。 现在返回的sarray副本列表将指向无效数据。 您需要定义自己的复制构造函数以制作列表指针的深层副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.