#include<iostream>
using namespace std;
//处理复数与double类型数的相加 ,结果存放在double型变量d1中,再以复数形式输出
class Complex
{
public:
Complex() { real = 0; imag = 0; } //默认构造函数
Complex(double r, double i); //构造函数 初始化real,imag
Complex(double); //转换构造函数(只有一个形参)
operator double() { return real; } //类型转换函数 (复数转换为double类型)
friend Complex operator+(Complex&, Complex&);
void display();
private:
double real;
double imag;
};
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
void Complex::display()
{
cout << real << "+" << imag << "i" << endl;
}
Complex::Complex(double r)
{
real = r;
imag = 0;
}
Complex operator+(Complex& c1, Complex& c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main()
{
double d1=2.5;
Complex c1(1, 2),c2;
d1 = d1 + c1;
cout << d1 << endl;
c2 = Complex(d1);
c2.display();
return 0;
}
谭浩强c++第三版10-6
最新推荐文章于 2024-08-15 05:02:54 发布