CPP
#include "del2.h"
Matrix::Matrix()
{
dArray = NULL;
}
bool Matrix::isValid() const
{
if (dArray == NULL)
return false;
return true;
}
Matrix::~Matrix()
{
delete [] dArray;
}
Matrix::Matrix(unsigned int nRows)
{
rows = nRows;
columns = nRows;
dArray = new double[nRows * nRows];
for (unsigned int i = 0; i < nRows; i++)
{
for (unsigned int n = 0; n < nRows; n++)
{
at(i,n) = 0;
}
}
at(0,0) = 1;
at(rows-1,columns-1) = 1;
}
Matrix::Matrix(unsigned int nRows, unsigned int nColumns)
{
dArray = new double[nRows * nColumns];
rows = nRows;
columns = nColumns;
for (unsigned int i = 0; i < nRows; i++)
for (unsigned int n = 0; n < nColumns; n++)
dArray[i * columns + n] = 0;
}
const Matrix Matrix::operator =(const Matrix & rhs)
{
columns = rhs.getColumns();
rows = rhs.getRows();
delete [] dArray;
dArray = new double[rows * columns];
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
at(row,column) = rhs.at(row,column);
return *this;
}
std::ostream & operator <<( std::ostream & out, const Matrix & classPrint )
{
if (!classPrint.isValid())
return out;
int rows = classPrint.getRows();
int columns = classPrint.getColumns();
out << std::endl;
for (int i = 0; i < rows; i++)
{
out << "| ";
for (int n = 0; n < columns; n++)
out << classPrint.at(i,n) << " ";
out << "|" << std::endl;
}
out << endl;
return out;
}
标题:
#ifndef DEL2
#define DEL2
#include <iostream>
using namespace std;
class Matrix
{
private:
int rows;
int columns;
double * dArray;
public:
~Matrix();
Matrix();
explicit Matrix(unsigned int nRows);
Matrix(unsigned int nRows, unsigned int nColumns);
const Matrix operator =(const Matrix & rhs);
const double at(int row, int column) const
{ return dArray[ row*this->columns + column ]; }
double & at( int row, int column )
{ return dArray[ row*this->columns + column ]; }
const int getRows() const {return rows;}
const int getColumns() const {return columns;}
bool isValid() const;
};
std::ostream & operator <<( std::ostream & out, const Matrix & classPrint );
#endif // MATRIX
主要的:
#include <iostream>
#include "del2.h"
using namespace std;
int main()
{
Matrix A;
Matrix B(10);
A = B;
cout << A;
return 0;
}
当我运行它时,会发生以下情况:
A 的第一个索引 matrix[0] 总是变成一些奇怪的数字,例如 2.22323e-306。我不明白为什么。即使我尝试设置“at(0,0) = 1;” 在运算符 = - 循环后的函数中,它仍然没有 0。