求教!先谢谢各位帮忙。

pixiu_lyf 2005-03-18 11:14:26
我写了个矩阵相乘的程序,重载运算符*为成员,那么this 指针能这样吗?
#include <iostream.h>
class matrix
{
public:
matrix();
matrix(int rr,int cc);
matrix(&ma);
~matrix();
void input();
void display();
matrix operator*(matrix&m);
float *getele(){return element;}
int getr(){return rowno;}
int getc(){return colno;}
private:
int rowno,colno;
float *element;

}
matrix::matrix(int rr,int cc)
{
rowno=rr;colno=cc;
element=new float[rr*cc];
}
matrix::matrix(&ma)
{
rowno=ma.rowno;
colno=ma.colno;
element=new float[ma.rowno*ma.colno];

}
matrix::~matrix()
{
delete[]element;
}
void matrix::input()
{
for(int i=0;i<rowno*colno;i++)
cin>>*(element+i);
}
void matrix::display()
{
for(int i=0;i<rowno;i++)
for(int j=0;j<colno;j++)
cout<<" "<<*(element+i*rowno+j)<<endl;
}
matrix matrix::operator*(matrix&m)
{
matrix result(rowno,m.getc());
for(int i=0;i<rowno;i++)
{
for(int k=0;k<m.getc();k++)
{
for(int j=0;j<colno;j++)
*(result.getele()+m.getc()*i+k)+=
(*(element+colno*i+j))*(*(m.getele()+m.getc()*j+k));
}
}
return result;

}

void main()
{
int row1No,col1No,col2No;

cout<<"Enter the row number of the first matrix:";
cin>>row1No;
cout<<"Enter the column number of the first matrix:";
cin>>col1No;
cout<<"Enter the column number of the second matrix:";
cin>>col2No;
matrix m1(row1No,col1No),m2(col1No,col2No),m3;
m1.input();
m2.input();
m1.display();
m2.display();
m3=m1*m2;
m3.display();

}
...全文
84 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhousqy 2005-03-18
  • 打赏
  • 举报
回复
可以
dongpy 2005-03-18
  • 打赏
  • 举报
回复
重载运算符*为成员是可以的。

不过一般不这么做。

这样声明更合理: friend const matrix operator*(const matrix&ml,const matrix&mr);

用全局函数代替成员函数。
yu2680020 2005-03-18
  • 打赏
  • 举报
回复
在沙发上正在沉思,请勿打扰!---结果是(应该可以),刚调试了一下。按您题目的意思 !
pixiu_lyf 2005-03-18
  • 打赏
  • 举报
回复
给dongpy(51-->ARM):
谢谢你。
我想理解this指针如何在我的重载函数里起作用。我上面程序运行的错误是
在构造函数这一行:
'matrix::matrix' : constructors not allowed a return type
在重载*函数里面第一行:
error in function definition or declaration; function not called
inlin 2005-03-18
  • 打赏
  • 举报
回复
不大了解

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧