我必须做一个项目,其中一个类 Row
有一个整数数组 int* OneArray
然后另一个类 Array
有一个数组第一类 Row* TwoDArray
。本质上,这个类有一个二维整数数组,当它在一个类中时,我可以很容易地构建二维数组。但是,现在我完全被难住了。
Row
的构造非常简单:
//set length of array
numOfRows = intRows;
//Create space for array
OneArray = new int[intRows];
//populate array with random numbers
for(int i=0; i<intRows; i++)
{
OneArray[i] = GenerateRandom(9,0);
}
这就是我卡住的地方(Array
的构造):
//Set Number of Cols
NumOfCol = intCols;
//create length for each row
int intLength = 4;
for(int i=0; i<NumOfCol; i++)
{
//create space and call row constructor with length
TwoDArray = new Row(intLength);
//increase length for jagged array
intLength++;
}
就像现在一样,它会在每次 for 循环后覆盖当前数组(这是预期的)。所以,我需要像 TwoDArray[i]
一样索引 TwoDArray
,但是一旦我尝试这样做,我就会收到此错误:
“从‘Row*’到‘const Row&’的无效用户定义转换。”
注意:如果我从 for 循环中取出该行,则只创建第一个数组,直到 intCol
才创建。 intLength
正在增加,因为我在技术上需要一个锯齿状数组,每个数组中的大小都不同。
我的类(class)是这样的:
class Row
{
public:
//Constructors
Row();
Row(int intRows);
Row(const Row& objPrev);
//Accessors
int getNumOfRows();
int getRowArray(int intRow);
//Mutators
void setRowArray(int intRow, int intChange);
//Destructor
~Row();
private:
int* OneArray;
int numOfRows;
}
和
class Array
{
public:
//Constructors
Array();
Array(int intRows, int intCols);
Array(const Array& objPrev);
//Accessors
int getNumOfCol();
Row getTwoDArray(int intCol, int intRow);
//Mutators
void setTwoDArray(int intCol, int intRow, int intChageTo);
//Destructor
~Array();
private:
Row* TwoDArray;
int NumOfCol;
}
如有任何帮助或建议,我们将不胜感激。
最佳答案
在 Array
中循环时,您多次分配一个 Row
对象,覆盖每个循环中的指针。这会导致内存泄漏,因为只有最后一个可以通过变量TwoDArray
获得。此外,在循环结束时,您将拥有一个仅包含单个元素的“数组”,即最后分配的 Row
对象。
问题是您不能在调用特定构造函数的同时使用new[]
进行数组分配。你可以不做例如
TwoDArray = new Row[NumOfCol](intLength);
相反,您必须将分配和初始化分成两部分:
TwoDArray = new Row[NumOfCol]; // Allocates memory, default constructed Row objects
for (int i = 0; i < NumOfCol; ++i)
{
TwoDArray[i] = Row(intLength); // Initialize each element
}
这当然需要您遵循 rules of three or five (or zero)以便循环中的复制工作。
关于c++ - 在不同的类 C++ 中构造类属性数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468844/