1. 程式人生 > >請編寫程式,處理一個複數與一個double數相加的運算,結果存放在一個double型的變數d1中,輸出d1的值,再以複數形式輸出此值。定義Complex(複數)類,在成員函式中包含過載型別轉換運算子:

請編寫程式,處理一個複數與一個double數相加的運算,結果存放在一個double型的變數d1中,輸出d1的值,再以複數形式輸出此值。定義Complex(複數)類,在成員函式中包含過載型別轉換運算子:

#include <iostream>

#include <iomanip>

using namespace std;

class Complex

{

public:

    Complex();

    Complex(double r);

    Complex(double r,double i);

    operator double();

    void display();

private:

    double real;

    double imag;

};

Complex::Complex(){}

Complex::Complex(double r)
{
	real=r;
	imag=0;
}

Complex::Complex(double r,double i)
{
	real=r;
	imag=i;
}

Complex::operator double()
{
	return real;
}

void Complex::display()
{
	cout<<"("<<real<<", "<<imag<<")"<<endl;
}

int main()

{

    cout<<setiosflags(ios::fixed);

    cout<<setprecision(2);

    double real,imag;

    cin>>real>>imag;

    Complex c1(real,imag);

    double d1;

    cin>>d1;

    d1=d1+c1;

    cout<<"d1="<<d1<<endl;

    Complex c2=Complex(d1);

    cout<<"c2=";

    c2.display();

    return 0;

}