类型转换函数(运算符函数重载)
#include <iostream>
using namespace std;
class complex
{
public:
complex():real(0),imag(0){}
complex(int r,int i):real(r),imag(i){}
void display();
operator double(){return real;}
friend complex operator +(const complex&,const complex&);
private:
int real;
int imag;
};
complex operator+(const complex&c1,const complex&c2)
{
return complex(c1.real+c2.real,c1.imag+c2.imag);
}
int main()
{
complex c1(3,4);
double d1=2.5+c1;
cout<<d1<<endl;
complex c2(1,2),c3(2,3);
double d2=c2+c3;
cout<<d2<<endl;
return 0;
}
结果