矩阵类的实现

时间:2025-01-15 14:44:33

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

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

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

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


二、代码

(1)头文件

#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 = ;
		row = ;
		size = ;
		data = new double [];
		for(int i=0; i<row; i++){
			for(int j=0; j<col; j++){
				data[i*row+j] = [i*row+j];
			}
		}

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

(2)源文件

#include<iostream>
#include ""
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);