| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1186 人关注过本帖
标题:[求助]代码求助,一道简单的编程题——减号运算符重载
只看楼主 加入收藏
lyz675059547
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2007-6-25
收藏
 问题点数:0 回复次数:0 
[求助]代码求助,一道简单的编程题——减号运算符重载

#include <iostream.h>
#include <stdlib.h>

class Matrix
{
int *p;
int row,col;
public:
Matrix(){row=col=0;p=NULL; }
Matrix(int,int);
void show();
void operator =(Matrix &m);
friend Matrix& operator +(Matrix &m1,Matrix &m2);
friend Matrix& operator -(Matrix &m1,Matrix &m2);
friend Matrix& operator *(Matrix &m1,Matrix &m2);
void transf();
~Matrix()
{
if (p) { delete []p;p=NULL; }
}
};

Matrix::Matrix(int m,int n)
{
int i,j,x;
if (m<=0 || n<=0)
{
cout<<"矩阵行、列数错误!\n";
row=col=0;
p=NULL;
}
else
{
row=m;col=n;
p=new int[row*col];
cout<<"创建矩阵对象:\n";
for (i=0;i<row;i++)
{
cout<<"请输入矩阵的第"<<i+1<<"行"<<col<<"个元素值:";
for (j=0;j<col;j++)
cin>>x,*(p+i*col+j)=x;
}
}
}

void Matrix::show()
{
int i,j;
if (p)
{
for (i=0;i<row;i++)
{
for (j=0;j<col;j++)
cout<<*(p+i*col+j)<<'\t';
cout<<endl;
}
}
}

void Matrix::operator =(Matrix &m)
{
if (p) delete[] p;
int i,k=m.row*m.col;
if (k>0)
{
p=new int[k];
for (i=0;i<k;i++)
p[i]=m.p[i];
row=m.row;
col=m.col;
}
else { p=NULL;row=col=0; }
}

Matrix& operator +(Matrix &m1,Matrix &m2)
{
static Matrix temp;
if (m1.row!=m2.row || m1.col!=m2.col)
{
cout<<"两矩阵不能相加!\n";
return temp;
}
int i,k=m1.row*m1.col;
if (k>0)
{
int *s;
s=new int[k];
for(i=0;i<k;i++)
s[i]=m1.p[i]+m2.p[i];
temp.p=s;
temp.row=m1.row;
temp.col=m1.col;
return temp;
}
return temp;
}

Matrix& operator -(Matrix &m1,Matrix &m2)
{
//请完成此函数的设计
}

Matrix& operator *(Matrix &m1,Matrix &m2)
{
static Matrix t;
int i,j,m,n,k;
m=m1.row;
n=m2.col;
if (m1.col!=m2.row)
{
cout<<"两矩阵不能相乘!\n";
return t;
}
if (m*n>0)
{
int *s=new int[m*n];
for (i=0;i<m;i++)
for (j=0;j<n;j++)
{
*(s+i*n+j)=0;
for (k=0;k<m1.col;k++)
*(s+i*n+j)+=*(m1.p+i*m1.col+k)**(m2.p+k*n+j);
}
t.p=s;t.row=m;t.col=n;
return t;
}
return t;
}
void Matrix::transf()
{
if (p)
{
int i,j,temp,*t;
if (row==col)
{
for (i=0;i<row;i++)
for (j=0;j<=i;j++)
{
temp=*(p+i*col+j); //p[i][j]
*(p+i*col+j)=*(p+j*col+i);
*(p+j*col+i)=temp;
}
}
else
{
t=new int[row*col];
for(i=0;i<row;i++)
for (j=0;j<col;j++)
*(t+j*row+i)=*(p+i*col+j);
i=row;row=col;col=i;
delete []p;
p=t;
}
}
}

void main(void)
{
Matrix m1(2,3),m2(2,3),m3(3,3),m4;
cout<<"\n矩阵m1:\n";
m1.show();
cout<<"\n矩阵m2:\n";
m2.show();
cout<<"\n矩阵m3:\n";
m3.show();
m4=m3;
cout<<"\n执行m4=m3后,矩阵m4:\n";
m4.show();
m4=m1+m2;
cout<<"\n矩阵m4=m1+m2:\n";
m4.show();
m4=m1*m3;
cout<<"\n矩阵m4=m1*m3:\n";
m4.show();
m1.transf();
cout<<"\n转置后的矩阵m1:\n";
m1.show();
m3.transf();
cout<<"\n转置后的矩阵m3:\n";
m3.show();
}
急用!请大家帮帮忙啊!先谢了啊!

搜索更多相关主题的帖子: 运算符 代码 重载 
2007-06-25 10:19
快速回复:[求助]代码求助,一道简单的编程题——减号运算符重载
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.013480 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved