#include<iostream> //复数的加法运算。
using namespace std;
class comp
{
private:
float real;
float imag;
public:
void set(float a,float b) {real=a,imag=b;}
void show() {cout<<real<<"+"<<imag<<"*i"<<endl;}
comp operator+(comp &i);
};
comp comp::operator+(comp &i) //引用传参。
{
comp t;
t.real=i.real+real;
t.imag=i.imag+imag;
return t;
}
int main()
{
comp i,j;
i.set(2.5,3.6);
j.set(5.5,6.8);
cout<<"i:";
i.show();
cout<<"j:";
j.show();//显示i,j的值。
comp t;
t=i+j;
cout<<"t:";
t.show();
return 0;
}
#include<iostream> //复数的加法运算。
using namespace std;
class comp
{
private:
float real;
float imag;
public:
void set(float a,float b) {real=a,imag=b;}
void show() {cout<<real<<"+"<<imag<<"*i"<<endl;}
friend comp operator+(comp &i,comp &j); //注意两个程序的此处的不同点。此处用了友元函数。
};
comp operator+(comp &i,comp &j) //引用传参。 //友元函数的定义。传的是两个参数,因为另一个参数并非comp类的this指针可以传递。
{
comp t;
t.real=i.real+j.real;
t.imag=i.imag+j.imag;
return t;
}
int main()
{
comp i,j;
i.set(2.5,3.6);
j.set(5.5,6.8);
cout<<"i:";
i.show();
cout<<"j:";
j.show();//显示i,j的值。
comp t;
t=i+j;
cout<<"t:";
t.show();
return 0;
}