65,211
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
using namespace std;
class Complex; //
ostream& operator<<(ostream& os,Complex& c); // 必需在定义友元函数 friend ostream& operator<< 之前声明该函数
class Complex
{
public:
friend ostream& operator<<(ostream& os,Complex& c); // 这里返回类型应该是ostream&
Complex(){real=0;imag=0;}
Complex(float r,float i):real(r),imag(i){}
Complex operator+(Complex&a)
{
Complex c;
c.real=real+a.real;
c.imag=imag+a.imag;
return c;
}
Complex operator-(Complex&a)
{
Complex c;
c.real=real-a.real;
c.imag=imag-a.imag;
return c;
}
float get_real(){return real;}
float get_imag(){return imag;}
private:
float real;
float imag;
};
ostream& operator<<(ostream& os, Complex& c)
{
os << c.real <<'+' << c.imag <<'i' << endl;
return os;
}
int main()
{
Complex c1(15,42),c2(74,65),c3;
c3=c1-c2;
cout << c3;
return 0;
}
friend ostream operator <<(ostream&os,Complex&c);
friend ostream& operator <<(ostream&os,Complex&c);
#include <iostream>
using namespace std;
class Complex
{
public:
friend ostream& operator <<(ostream& os,Complex &c); //这里返回类型是ostream&
Complex(){real=0;imag=0;}
Complex(float r,float i):real(r),imag(i){}
Complex operator+(Complex &a)
{
Complex c;
c.real=real+a.real;
c.imag=imag+a.imag;
return c;
}
Complex operator-(Complex &a)
{
Complex c;
c.real=real-a.real;
c.imag=imag-a.imag;
return c;
}
float get_real(){return real;}
float get_imag(){return imag;}
private:
float real;
float imag;
};
ostream& operator <<(ostream &os,Complex &c )
{
os <<c.real <<'+' <<c.imag <<'i' <<endl;
return os;
}
int main()
{
Complex c1(15,42),c2(74,65),c3;
c3=c1-c2;
cout <<c3;
return 0;
}