在VC++重载中遇到的问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 14:20:24
#include <iostream.h>
class Matrix
{
public:
Matrix( );
friend operator + (Matrix &,Matrix &);
friend ostream& operator << (ostream&,Matrix &);
friend istream& operator >> (istream&,Matrix &);
void display();
private:
int mat[2][3];
};

Matrix::Matrix( )
{
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
mat[i][j]=0;
}

operator + (Matrix &a,Matrix &b)
{
Matrix c;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
{
c.mat[i][j]=a.mat[i][j]+b.mat[i][j];
}
return c;

}

ostream& operator << (ostream &output,Matrix &m)
{
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
output<<m.mat[i][j];
return output;
}

istream& operator >>(istream &input,Matrix &m)
{
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)

你把相加操作符重载:
friend operator + (Matrix &,Matrix &);
加一个返回Matrix&,就像这样
friend Matrix& operator + (Matrix &,Matrix &);
再相应的在它的实现部分也加上这个
Matrix& operator + (Matrix &a,Matrix &b)
就没有错了。

friend operator + (Matrix &,Matrix &);

改成

friend Matrix operator + (Matrix &,Matrix &);

同理

Matrix operator + (Matrix &a,Matrix &b)

记得用友元函数重载两个参量的加号就没成功过。。。
最后都是用一个参量的重载加号