⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 matrix.cpp

📁 Matrix code
💻 CPP
字号:
#include <iostream>
#include <iomanip>

using namespace std;

class Matrix{
public:
	Matrix(int row,int col);
	Matrix(const Matrix& other);
	~Matrix();
	Matrix& operator=( const Matrix& other);
	double& operator()( int x,int y);
	friend Matrix operator+( Matrix& first,  Matrix& second);
	friend Matrix operator*( Matrix& first,  Matrix& second);
	friend ostream& operator<<( ostream& out, Matrix& matrix);
private:
	double* data;
	int row,int col;
};

Matrix::Matrix(int row,int col)
{
	this->row=row;
	this->col=col;
	data=new double[row*col];
	for( int i=0; i<row*col; i++ )
		data[i]=0;
}

Matrix::Matrix(const Matrix& other)
{
	row=other.row;
	col=other.col;
	data=new double[row*col];
	for( int i=0; i<row*col; i++ )
		data[i]=other.data[i];
}

Matrix::~Matrix()
{
	delete[] data;
}

Matrix& Matrix::operator=( const Matrix& other)
{
	if( this==&other ) return *this;
	delete data;
	row=other.row;
	col=other.col;
	data=new double[row*col];
	for( int i=0; i<row*col; i++ )
		data[i]=other.data[i];
}

double& Matrix::operator()(int x,int y)
{
	if( x<0 || x>=row ){
		cout<<"Row index out of bounds!\n";
		exit(1);
	}
	if( y<0 || y>=col ){
		cout<<"Col index out of bounds!\n";
		exit(1);
	}
	return data[x*col+y];
}

Matrix operator+( Matrix& first,  Matrix& second)
{
	if( first.row!=second.row || first.col!=second.col )
		return Matrix(1,1);
	Matrix result(first.row,first.col);
	
	for( int i=0; i<result.row; i++ )
		for( int j=0; j<result.col; j++ )
			result(i,j)=first(i,j)+second(i,j);
		return result;
}

Matrix operator*( Matrix& first,  Matrix& second)
{
	if( first.col!=second.row )
		return Matrix(1,1);
	Matrix result(first.row,first.col);
	
	for( int i=0; i<result.row; i++ )
		for( int j=0; j<result.col; j++ )
		{
			result(i,j)=0;
			for( int k=0; k<first.col; k++ )
				result(i,j)=result(i,j)+first(i,k)*second(k,j);
		}
	return result;
}

ostream& operator<<( ostream& out, Matrix& matrix)
{
	for( int i=0; i<matrix.row; i++){
		for( int j=0; j<matrix.col; j++ ) 
			out<<setw(6)<<matrix(i,j);
		out<<endl;
	}
	return out;
}

int main()
{
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -