2443: C++习题 复数类--重载运算符3+
时间限制: 1 Sec 内存限制: 128 MB
提交: 1368 解决: 733
题目描述
请编写程序,处理一个复数与一个double数相加的运算,结果存放在一个double型的变量d1中,输出d1的值,再以复数形式输出此值。定义Complex(复数)类,在成员函数中包含重载类型转换运算符:
operator double() { return real; }
输入
一个复数与一个double数
输出
d1的值和复数形式的此值
样例输入
3 4
2.5
样例输出
d1=5.50
c2=(5.50, 0.00)
提示
前置代码及类型定义已给定如下,提交时不需要包含,会自动添加到程序前部
/* C++代码 */
#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;
};
主函数已给定如下,提交时不需要包含,会自动添加到程序尾部
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(){}
Complex::operator double()
{
return real;
}
Complex::Complex(double r)
{
real=r;
imag=0;
}
Complex::Complex(double r,double i)
{
real=r;
imag=i;
}
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(){}
Complex::operator double()
{
return real;
}
Complex::Complex(double r)
{
real=r;
imag=0;
}
Complex::Complex(double r,double i)
{
real=r;
imag=i;
}
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;
}