用指针数组重载输入操作符

Overloading the input operator with an array of pointers

本文关键字:输入 操作符 重载 数组 指针      更新时间:2023-10-16

对于一个类项目,我有一个2D指针数组。我理解构造函数,析构函数等,但我有问题理解如何设置数组中的值。我们使用了重载输入操作符来输入值。到目前为止,我为这个操作符编写的代码是:

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转换为矩阵::compArrayPtr(又名Complex*)在分配"如果有人能解释我做错了什么,我会非常感激。

您的newComplexComplex类型的对象(值),您试图将其分配给Complex*指针。

要做到这一点,你应该动态地构造一个complex:

Complex* newComplex = new Complex();
input >> *newComplex;
matrix.complexArray[i] = newComplex;

但是要注意动态分配带来的所有后果(内存管理、所有权、共享状态…)