课后习题求大神指点。
定义一个负数类 complex,并重载“+”,实现复数的相加,但是不能把“+”重载为友元函数和成员函数,下面是我写的两个代码,第一个可以运行但是第二个不能运行求指点!!#include<iostream>
using namespace std;
class complex
{
public:
complex(){real=0;image=0;}
complex(int r,int i):real(r),image(i){}
int disreal();
int disimage();
void display();
private:
int real;
int image;
};
int complex::disreal()
{
return(real);
}
int complex::disimage()
{
return(image);
}
void complex::display()
{
cout<<real<<"+"<<image<<endl;
}
complex operator +(complex &c1,complex &c2)
{
return complex(c1.disreal()+c2.disreal(),c1.disimage()+c2.disimage());
}
int main()
{
complex c1(4,3),c2(3,5),c3;
c3=c1+c2;
c3.display();
return(0);
}
这是第一个可以运行。
#include<iostream>
using namespace std;
class complex
{
public:
complex(){real=0;image=0;}
complex(int r,int i):real(r),image(i){}
friend ostream& operator <<(ostream&,complex&);
int disreal();
int disimage();
private:
int real;
int image;
};
int complex::disreal()
{
return(real);
}
int complex::disimage()
{
return(image);
}
ostream& operator <<(ostream &output,complex &c3)
{
output<<c3.real<<c3.image<<endl;
return output;
}
complex operator +(complex &c1,complex &c2)
{
return complex(c1.disreal()+c2.disreal(),c1.disimage()+c2.disimage());
}
int main()
{
complex c1(4,3),c2(3,5),c3;
c3=c1+c2;
cout<<c3;
return(0);
}
第二个我重载了<<使它能输出complex类,但是不知道为啥不能运行。