马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
[code]#ifndef CMATRIX_H
#define CMATRIX_H
class CMatrix{
public:
CMatrix(int r,int c);
~CMatrix(){};
void create();
void output();
CMatrix operator +(CMatrix &M1);
CMatrix operator -(CMatrix &M1);
CMatrix operator *(CMatrix &M1);
CMatrix tran();
private:
int row;
int col;
int **arr;
};
#endif
#include<iostream>
#include"CMatrix.h"
using namespace std;
CMatrix::CMatrix(int r,int c){
row=r;
col=c;
arr=new int*[r];
for(int i=0;i<row;i++){
arr[i]=new int[c];
}
for(i=0;i<row;i++){
for(int j=0;j<col;j++){
arr[i][j]=0;
}
}
}
void CMatrix::create(){
cout<<"请输入矩阵的值"<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cin>>arr[i][j];
}
}
}
void CMatrix::output(){
cout<<"打印矩阵"<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<arr[i][j]<<"\t";
}
cout<<endl;
}
}
CMatrix CMatrix::operator +(CMatrix &M1){
CMatrix M2(row,col);
if(row!=M1.row||col!=M1.col){
cout<<"不符合矩阵相加规则"<<endl;
}else{
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
M2.arr[i][j]=arr[i][j]+M1.arr[i][j];
}
}
}
return M2;
}
CMatrix CMatrix::operator -(CMatrix &M1){
CMatrix M2(row,col);
if(row!=M1.row||col!=M1.col){
cout<<"不符合矩阵相减规则"<<endl;
}else{
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
M2.arr[i][j]=arr[i][j]-M1.arr[i][j];
}
}
}
return M2;
}
CMatrix CMatrix::operator *(CMatrix &M1){
CMatrix M2(row,M1.col);
if(col!=M1.row){
cout<<"不符合乘法规则"<<endl;
}else{
for(int i=0;i<row;i++){[code]#include<iostream>
#include<stdlib.h>
#include"CMatrix.h"
using namespace std;
int main(){
int x,y;
cout<<"输入行和列"<<endl;
cin>>x>>y;
CMatrix m1(x,y);
m1.create();
m1.output();
cout<<"矩阵的转置"<<endl;
m1.tran().output();
CMatrix m2(x,y);
cout<<"输入矩阵B的值"<<endl;
m2.create();
m2.output();
CMatrix m3(y,x);
cout<<"输入矩阵C的值"<<endl;
m3.create();
m3.output();
cout<<"矩阵的加法"<<endl;
CMatrix M4=m1+m2;
M4.output();
cout<<"矩阵的减法"<<endl;
CMatrix M5=m1+m2;
M5.output();
cout<<"矩阵的乘法"<<endl;
CMatrix M6=m1*m3;
M6.output();
system("pause");
return 0;
}
for(int j=0;j<M1.col;j++){
for(int k=0;k<col;k++){
M2.arr[i][j]+=arr[i][k]*M1.arr[k][j];
}
}
}
}
return M2;
}
CMatrix CMatrix::tran(){
CMatrix M2(col,row);
for(int i=0 ;i<col;i++){
for(int j=0;j<row;j++){
M2.arr[i][j]=arr[j][i];
}
}
return M2;
}[/code][/code] |