矩阵类的实现

一、实现矩阵类及以下功能

(1)编写一个 row*col 的矩阵类,定义构造函数、复制构造函数;

(2)重载运算符“+”和“-”实现矩阵的相应运算;

(3)重载运算符<<实现矩阵数据的输出。


二、代码

(1)头文件 matrix.h

#include<iostream>
using namespace std;

class Matrix{
private:
	int row;
	int col;
	int size;
	double* data;

public:
	Matrix(int r,int c){
		row = r;
		col = c;
		size = row * col;
		data = new double[size];
		cout<<"请输入"<<row<<"*"<<col<<"矩阵:"<<endl;
		for(int i=0; i<row; i++){
			for(int j=0; j<col; j++){
				cin >> data[i*row+j];
			}
		}
	}

	~Matrix(void){
		delete []data;
	}
	Matrix (const Matrix& M)
	{
		col = M.col;
		row = M.row;
		size = M.size;
		data = new double [M.size];
		for(int i=0; i<row; i++){
			for(int j=0; j<col; j++){
				data[i*row+j] = M.data[i*row+j];
			}
		}

	}
	Matrix& operator=(Matrix& M)
	{
		if (this == &M)
		{
			return *this;
		}
		col = M.col;
		row = M.row;
		size = M.size;
		data = new double [M.size];
		for(int i=0; i<row; i++){
			for(int j=0; j<col; j++){
				data[i*row+j] = M.data[i*row+j];
			}
		}
		return *this;
	}
	Matrix operator+(Matrix& M){
		Matrix M1 = *this;
		if(col == M.col && row == M.row){
			for(int i=0; i<M1.row; i++){
				for(int j=0; j<M1.col; j++){
					M1.data[i*row+j] = data[i*row+j] + M.data[i*row+j];
				}
			}
			return M1;
		}
		else{
			cout << "矩阵行或列数不相等,不能相加" << endl;
			return M1;
		}
	}
	Matrix operator-(Matrix& M){
		Matrix M1 = *this;
		if(col == M.col && row == M.row){
			for(int i=0; i<M1.row; i++){
				for(int j=0; j<M1.col; j++){
					M1.data[i*row+j] = data[i*row+j] - M.data[i*row+j];
				}
			}
			return M1;
		}
		else{
			cout << "矩阵行或列数不相等,不能相减" << endl;
			return M1;
		}
	}
	friend ostream& operator<<(ostream& out,Matrix& M){
		for(int i=0; i<M.row; i++){
			for(int j=0; j<M.col; j++){
				out << M.data[i*M.row+j] << ' ';
			}
			out << endl;
		}
		return out;
	}
};

(2)源文件 main.cpp

#include<iostream>
#include "matrix.h"
using namespace std;

int main(void){
	Matrix M1(4,4);
	Matrix M2(4,4);
	Matrix M3 = M1;
	Matrix M4 = M1 + M2;
	Matrix M5 = M3 - M2;
	cout << "M1:"<<endl << M1 << endl;
	cout << "M2:"<<endl << M2 << endl;
	cout << "M3 = M1:"<<endl << M3 << endl;
	cout << "M4 = M1 + M2:"<<endl << M4 << endl;
	cout << "M5 = M3 - M2:"<<endl << M5 << endl;
	return 0;
}

三、引入类模板的改进

template <class T>
class Matrix{
private:
	int row;
	int col;
	int size;
	T* data;

public:
	Matrix(int r,int c){
		row = r;
		col = c;
		size = row * col;
		data = new T[size];
		cout<<"请输入"<<row<<"*"<<col<<"矩阵:"<<endl;
		for(int i=0; i<row; i++){
			for(int j=0; j<col; j++){
				cin >> data[i*row+j];
			}
		}
	}

顺便说下模板的实例化如下

 Matrix<float> M(4,4);
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值