增加了二维动态数组
Addition of 2D Dynamic Arrays
我有一个类项目,是制作和操作动态对象。我有一个叫做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++)
相关文章:
- 二维动态数组逻辑
- 在C++中通过引用传递字符串的二维动态数组
- 创建二维动态数组的函数
- 如何初始化所有元素为 0 的指针的二维动态内存数组
- cpp二维动态数组
- 在C++中的类内部创建的二维动态分配数组
- 基类和派生类的二维动态数组
- 初始化所有条目为 0 的二维动态数组
- 一个二维动态阵列的C++剖分与比较
- 如何将项目添加到二维动态矢量
- 二进制 I/O 到具有二维动态数组的文件
- 二维动态容器 qt
- 如何在 C++ 中的类中声明二维动态数组
- 转置二维动态矩阵
- 是二维动态对象 O(n^2) 碰撞的最快算法
- 如何理解这个二维动态数组的实现?这是最基本的实现
- 如何在c++中设置具有特定值的二维动态数组
- 增加了二维动态数组
- 长双二维动态数组c++
- 从二维动态数组中获取长度