题目:编写程序实现实数矩阵类。
要求:实现矩阵的加法、减法、乘法
分析:运用重载运算符的方法,对<<、>>+、-、*进行重载
//Matrix.h
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include<iostream>
class Matrix
{
friend std::istream& operator>>(std::istream& in,Matrix &c);
friend std::ostream& operator<<(std::ostream& out,const Matrix &c);
friend Matrix operator+(const Matrix &c1, const Matrix &c2);
friend Matrix operator-(const Matrix &c1, const Matrix &c2);
friend Matrix operator*(const Matrix &c1, const Matrix &c2);
int *elem;
int row;
int col;
public:
Matrix(int r =0,int c=0):row(r),col(c)
{
elem = new int[r*c];
}
~Matrix();
};
#endif // MATRIX_H_INCLUDED
//Matrix.cpp
#include<iostream>
#include "Matrix.h"
#include<string.h>
Matrix::~Matrix()
{
delete[]elem;
}
std::istream& operator>>(std::istream& in, Matrix &c)
{
for(int i=0; i<c.row; i++)
{
for(int j=0;j<c.col;j++)
{
in>>c.elem[i*c.col + j];
}
}
return in;
}
std::ostream& operator<<(std::ostream& out,const Matrix &c)
{
for(int i=0;i<c.row;i++)
{
for(int j=0;j<c.col;j++)
{
out << c.elem[i*c.col + j] << ' ';
}
out<<std::endl;
}
out<<std::endl;
return out;
}
Matrix operator+(const Matrix &c1, const Matrix &c2)
{
Matrix tmp(c2.row, c2.col);
for(int i=0;i<c1.row;i++)
{
for(int j=0;j<c1.col;j++)
{
tmp.elem[i*c2.col + j] = c1.elem[i*c2.col + j] + c2.elem[i*c2.col + j];
}
}
return tmp;
}
Matrix operator-(const Matrix &c1, const Matrix &c2)
{
Matrix tmp(c2.row, c2.col);
for(int i=0;i<c1.row;i++)
{
for(int j=0;j<c1.col;j++)
{
tmp.elem[i*c2.col + j] = c1.elem[i*c2.col + j] - c2.elem[i*c2.col + j];
}
}
return tmp;
}
Matrix operator*(const Matrix &c1, const Matrix &c2)
{
Matrix tmp(c1.row, c2.col);
int x=0;
for(int i=0;i<c1.row;i++)
{
for(int j=0;j<c2.col;j++)
{
for(int n=0;n<c2.row;n++)
{
x += c1.elem[i*c1.col+n] * c2.elem[n*c2.col+j];
}
tmp.elem[i*c2.col+j] = x;
x=0;
}
}
return tmp;
}
//main.cpp
#include<iostream>
#include"Matrix.h"
int main()
{
Matrix c1(3,3);
Matrix c2(3,1);
std::cin>>c1;
std::cin>>c2;
//std::cout<<c1+c2;
//std::cout<<c1-c2;
std::cout<<c1*c2;
//std::cout<<c1/c2;
}