我正在尝试将动态分配的数组复制到实例。我的代码似乎正在复制值,但是还需要调整数组的大小以匹配“&other”大小的数组。
有关代码的一些信息:手头有两个类,一个是“电影”,它以标题,电影时间和导演(所有指针)作为私有成员。还有另一个称为“ MovieCollection”的数组,该数组将“ Movie”的每个实例存储在给定索引中。
//These are private member variables:`
int ArrySize = 50; //There is another section of code that points to this and resizes if needed, I believe it needed a size at runtime though.
//Array to store instance of "movie"
Movie *movieArry = new Movie[ArrySize];
//This is assignment operator
const MovieCollection& operator=(const MovieCollection& other)
{
delete []movieArray;
int otherSizeArry = other.ArrySize;
Movie* temp;
temp = new Movie[otherSizeArry];
for (int i = 0; i < otherSizeArry; i++)
temp[i] = other.movieArry[i];
return *this;
delete []temp;
}
创建实例时,我使用了编写的另一个函数来调整数组大小。例如,我要复制的实例有10个索引,但是我尝试将值复制到的新实例仍然有50个限制。据我了解,由于无法调整数组大小,因此必须删除它,然后复制新尺寸(以及值)。
任何帮助将不胜感激,并在此先感谢您。另外,如果需要更多代码,对不起。我不想付出超出所需的一切。
您的赋值运算符实施不正确。它movieArray
在分配新temp
数组之前释放数组。如果分配失败,则该类将处于错误状态。而且您没有在调用之前将temp
数组分配给它(这是永远不会达到的,编译器应该已经对此发出警告)。movieArray
return *this;
delete []temp
操作员应该看起来像这样:
MovieCollection& operator=(const MovieCollection& other)
{
if (&other != this)
{
int otherSizeArry = other.ArrySize;
Movie* temp = new Movie[otherSizeArry];
for (int i = 0; i < otherSizeArry; ++i) {
temp[i] = other.movieArry[i];
}
// alternatively:
// std::copy(other.movieArry, other.movieArry + otherSizeArry, temp);
std::swap(movieArray, temp);
ArrySize = otherSizeArry;
delete[] temp;
}
return *this;
}
如果您的类有一个复制构造函数(如果没有,则需要添加一个),可以大大简化赋值运算符的实现:
/*
MovieCollection(const MovieCollection& other)
{
ArrySize = other.ArrySize;
movieArray = new Movie[ArrySize];
for (int i = 0; i < ArrySize; ++i) {
movieArray[i] = other.movieArry[i];
}
// alternatively:
// std::copy(other.movieArry, other.movieArry + ArrySize, movieArray);
}
*/
MovieCollection& operator=(const MovieCollection& other)
{
if (&other != this)
{
MovieCollection temp(other);
std::swap(movieArray, temp.movieArray);
std::swap(ArrySize, temp.ArrySize);
}
return *this;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句