1274 面向对象程序设计上机练习十二(运算符重载)
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
处理一个复数与一个double数相加的运算,结果存放在一个double型变量d1中,输出d1的值。定义Complex(复数)类,在成员函数中包含重载类型转换运算符:operator double(){return real;}
Input
输入占两行:
第1行是一个复数的实部和虚部,数据以空格分开。
第2行是一个实数。
Output
输出占一行,复数的实部和实数之和,小数点后保留1位。
Example Input
2.3 5.43.4
Example Output
5.7
#include <bits/stdc++.h>
using namespace std;
class Complex
{
public:
Complex(double x = 0, double y = 0)
{
real = x;
imag = y;
}
void get_in1(double x = 0, double y = 0)
{
cin >> x >> y;
real = x;
imag = y;
}
void get_in2(double x = 0, double y = 0)
{
cin >> x;
real = x;
imag = y;
}
void put_out()
{
cout << fixed << setprecision(1) <<real <<endl;
}
Complex operator + (Complex &t)
{
Complex x;
x.real = t.real + real;
x.imag = t.imag + imag;
return x;
}
private:
double real,imag;
double x,y;
};
int main()
{
Complex c1,c2,c3;
c1.get_in1();
c2.get_in2();
c3 = c1 + c2;
c3.put_out();
return 0;
}