对于一个类项目,我有一个二维指针数组。我了解构造函数、析构函数等,但在理解如何设置数组中的值时遇到问题。我们使用重载的输入运算符来输入值。到目前为止,这是我为该操作员提供的代码:
istream& operator>>(istream& input, Matrix& matrix)
{
bool inputCheck = false;
int cols;
while(inputCheck == false)
{
cout << "Input Matrix: Enter # rows and # columns:" << endl;
input >> matrix.mRows >> cols;
matrix.mCols = cols/2;
//checking for invalid input
if(matrix.mRows <= 0 || cols <= 0)
{
cout << "Input was invalid. Try using integers." << endl;
inputCheck = false;
}
else
{
inputCheck = true;
}
input.clear();
input.ignore(80, '\n');
}
if(inputCheck = true)
{
cout << "Input the matrix:" << endl;
for(int i=0;i< matrix.mRows;i++)
{
Complex newComplex;
input >> newComplex;
matrix.complexArray[i] = newComplex; //this line
}
}
return input;
}
显然我在这里的赋值语句是不正确的,但我不确定它应该如何工作。如果有必要包含更多代码,请告诉我。这是主构造函数的样子:
Matrix::Matrix(int r, int c)
{
if(r>0 && c>0)
{
mRows = r;
mCols = c;
}
else
{
mRows = 0;
mCols = 0;
}
if(mRows < MAX_ROWS && mCols < MAX_COLUMNS)
{
complexArray= new compArrayPtr[mRows];
for(int i=0;i<mRows;i++)
{
complexArray[i] = new Complex[mCols];
}
}
}
这里是 Matrix.h,所以你可以看到属性:
class Matrix
{
friend istream& operator>>(istream&, Matrix&);
friend ostream& operator<<(ostream&, const Matrix&);
private:
int mRows;
int mCols;
static const int MAX_ROWS = 10;
static const int MAX_COLUMNS = 15;
//type is a pointer to an int type
typedef Complex* compArrayPtr;
//an array of pointers to int type
compArrayPtr *complexArray;
public:
Matrix(int=0,int=0);
Matrix(Complex&);
~Matrix();
Matrix(Matrix&);
};
#endif
我得到的错误是“无法在分配中将 Complex 转换为 Matrix::compArrayPtr (aka Complex*)”如果有人能解释我做错了什么,我将不胜感激。