矩阵类的实现

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

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

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

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


二、代码

(1)头文件 matrix.h

#include
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<<"请输入"<> 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

(2)源文件 main.cpp

#include
#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:"<

三、引入类模板的改进

template 
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<<"请输入"<> data[i*row+j];
			}
		}
	}

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

 Matrix M(4,4);

你可能感兴趣的:(编程思想,C++)