希望大家能夠一起討論,把矩陣這個類給完善。
#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;
}