希望大家能够一起讨论,把矩阵这个类给完善。
#include <iostream>
using namespace std;
class Matrix
{
private:
int rows,columns;
int **pMatrix;
public:
Matrix(int rows = 3,int columns = 2);
Matrix(const Matrix &M);
~Matrix();
Matrix& operator=(const Matrix& M);
int GetRows() const;
int GetColumns() const;
void SetValue();
friend Matrix operator*(const Matrix& a,const Matrix& b);
friend ostream& operator<<(ostream& os,const Matrix& M);
};
int Matrix::GetRows() const { return rows;}
int Matrix::GetColumns() const { return columns;}
// 构造函数
Matrix::Matrix(int x,int y)
{
rows = x;
columns = y;
//有的时候为了考虑创建对象的效率,在使用的时候分配存储空间,而不在构造函数中分配
pMatrix = new int* [x];
for (int i = 0 ; i < x; i++ )
{
pMatrix[i] = new int[y];
for(int j = 0;j < y;j++) //初始化每个值为0
pMatrix[i][j] = 0;
}
}
// 析构函数
Matrix::~Matrix()
{
for (int i = 0 ;i < rows;i ++ )
delete[] pMatrix[i];
delete[] pMatrix;
}
// 赋值函数
Matrix& Matrix::operator=(const Matrix& M)
{
if(this != &M)
{
for (int ii = 0 ;ii < rows;ii++ )
if(pMatrix[ii])
delete[] pMatrix[ii];
if(pMatrix)
delete[] pMatrix;
rows = M.rows;
columns = M.columns;
//分配存储空间
pMatrix = new int* [rows];
for (int k = 0 ; k < rows; k++ )
pMatrix[k] = new int[columns];
for ( int i = 0 ; i < rows; i ++ )
for ( int j = 0 ; j < columns; j ++ )
pMatrix[i][j] = M.pMatrix[i][j];
}
return *this;
}
void Matrix::SetValue()
{
int i,j,value;
for ( i = 0 ; i < rows; i ++ )
{
for ( j = 0 ; j < columns; j ++ )
{
cout << " 第 " << i << " 行 " ;
cout << " 第 " << j << " 列: " ;
cin >> value;
cout << endl;
pMatrix[i][j] = value;
}
}
}
// 拷贝构造函数
Matrix::Matrix(const Matrix& M)
{
rows = M.rows;
columns = M.columns;
//分配存储空间
pMatrix = new int* [rows];
for (int k = 0 ; k < rows; k++ )
pMatrix[k] = new int[columns];
for ( int i = 0 ; i < rows; i ++ )
for ( int j = 0 ; j < columns; j ++ )
pMatrix[i][j] = M.pMatrix[i][j];
}
Matrix operator*(const Matrix& a,const Matrix& b)
{
if (a.columns == b.rows)
{
Matrix c(a.rows,b.columns);
for ( int i = 0 ;i < a.rows;i ++ )
{
for ( int j = 0 ;j < b.columns;j ++ )
{
for ( int columnIndex= 0 ;columnIndex < a.columns;columnIndex++ )
c.pMatrix[i][j] += a.pMatrix[i][columnIndex] * b.pMatrix[columnIndex][j];
}
}
return c;
}
else
return Matrix();
}
ostream& operator<<(ostream& os,const Matrix& M)
{
for (int i = 0;i < M.rows;i++ )
{
for (int j = 0;j < M.columns;j++ )
os << M.pMatrix[i][j] << " ";
os << endl;
}
return (os << endl);
}
// 主函数
void main()
{
Matrix Ma(3,2),Mb(2,2);
Ma.SetValue();
Mb.SetValue();
cout << Ma << endl;
cout << Mb << endl;
Matrix Mc = Ma * Mb;//拷贝构造函数
cout << Mc << endl;
Mc = Mb; //=运算符,即赋值函数
cout << Mb << endl;
}