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

时间:2013-04-27 18:31:55

标签: c++ pointers

对于一个类项目我有一个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

我得到的错误是“无法将复合转换为Matrix :: compArrayPtr(又称复杂*)”如果有人能解释我做错了什么,我将非常感激。

1 个答案:

答案 0 :(得分:1)

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

为此,你应该动态构建一个复合体:

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

但请注意动态分配带来的所有后果(内存管理,所有权,共享状态......)。

相关问题