У меня есть проект класса, который должен создавать и работать с динамическими объектами. У меня есть класс Matrix, который использует 2-мерный указательный массив для хранения объекта типа Complex (который представляет собой сложный класс чисел). Мне нужно иметь возможность добавлять 2 массива, добавляя все значения в массивы вместе и возвращая новый массив. Проблема в том, что я не понимаю синтаксис доступа к каждому сложному объекту в массиве. Вот то, что я до сих пор для перегруженного добавления оператора:Добавление 2D динамических массивов
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];
}
}
}
Как и сейчас, программа компилируется, но перестает работать, когда приходит к добавлению матриц во время выполнения. Если кто-нибудь скажет мне, какой синтаксис я должен использовать и почему, это было бы очень полезно.