习题 10.6 请编写程序,处理一个复数与一个double数相加的运算,结果存放在一个double型的变量d1中,输出d1的值,再以复数形式输出此值。定义Complex(复数)类,在成员函数中包含重载类型转换运算符:
operator double()
{
return real;
}
代码:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex() { real = 0; imag = 0; }
Complex(double r) { real = r; imag = 0; } //类型转换构造函数
Complex(double r, double i) { real = r; imag = i; }
operator double() //类型转换函数
{
return real;
}
void display();
private:
double real;
double imag;
};
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
Complex c1(3, 4),c2;
double d = 2.0, d1;
d1 = d + c1;
cout << d1 << endl;
c2 = Complex(d1);
c2.display();
return 0;
}