贺老师的教学链接 本课讲解
//类型转换函数应用
#include <iostream>
using namespace std;
class Complex
{
public:
Complex( )
{
real=0;
imag=0;
}
Complex(double r,double i)
{
real=r;
imag=i;
}
operator double( );
friend Complex operator + (Complex c1,Complex c2);
private:
double real;
double imag;
};
Complex operator + (Complex c1,Complex c2) //定义运算符“+”重载函数
{
return Complex(c1.real+c2.real, c1.imag+c2.imag);
}
Complex::operator double( )
{
return real;
}
int main( )
{
Complex c1(3.5,4),c2(5,-10);
double d1,d2;
d1=2.5+c1;
cout<<d1<<endl;
d2=c1+c2;
cout<<d2<<endl;
return 0;
}