增加了二维动态数组

Addition of 2D Dynamic Arrays

本文关键字:二维 动态 数组 增加      更新时间:2023-10-16

我有一个类项目,是制作和操作动态对象。我有一个叫做Matrix的类,它使用一个二维指针数组来存储Complex类型的对象(这是一个复数类)。我需要能够通过将数组中的所有值加在一起并返回一个新数组来添加2个数组。问题是我不理解访问数组中每个Complex对象的语法。以下是目前为止重载的加法操作符:

const Matrix Matrix::operator+(const Matrix& rhs) const
{
    Matrix newMatrix(mRows,mCols); 
    for(int i=0;i<mRows;i++) 
    {
        for(int j=0;j<mCols;j++) 
        {
            (*newMatrix.complexArray[i]) = (*complexArray[i])+    (*rhs.complexArray[i]);
        }   
    }
return newMatrix;
}

下面是Matrix对象的重载输入操作符:

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+matrix.mCols);i++) 
    {
        Complex* newComplex = new Complex();
        input >> *newComplex;
        matrix.complexArray[i] = newComplex;
    }
}
return input;
}

下面是Matrix类的定义:

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;
            Complex **complexArray;
public:
            Matrix(int=0,int=0);
            Matrix(Complex&);
            ~Matrix();
            Matrix(Matrix&);
            Matrix& operator=(const Matrix&);
            const Matrix operator+(const Matrix&) const;
};

和构造函数:

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 Complex[mRows];
    complexArray= new Complex*[mRows];
    for(int i=0;i<mRows;i++)
    {
        complexArray[i] = new Complex[mCols];
    }
}
}

就像现在一样,程序可以编译,但是当它在运行时添加矩阵时停止工作。如果有人能告诉我应该使用什么语法以及为什么,那将非常有帮助。

你似乎没有接受足够的输入。您正在使用(行+cols)复数作为输入,但随后尝试(正确)遍历矩阵内的(行*cols)元素。

for(int i=0;i< (matrix.mRows+matrix.mCols);i++) 

for(int i=0;i<mRows;i++) 
    {
        for(int j=0;j<mCols;j++)