# C++习题 复数类--重载运算符3+

C++习题 复数类--重载运算符3+

operator double() { return real; }

d1的值和复数形式的此值

``````3 4
2.5
``````

``````d1=5.50
c2=(5.50, 0.00)``````

``````
#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()
{
real=0;
imag=0;
}
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;
}
``````

``````
#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(double r)
{
imag=0;
real=r;
}
Complex::Complex(double r,double i)
{
imag=i;
real=r;
}
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;
}
``````