定义复数类Complex,并重载运算符:+、-,实现一个整数与复数类对象的加减运算。定义成员函数print,调用该函数时,以格式“(real,imag)”输出当前对象的实部和虚部,例如:对象的实部和虚部分别是4.2和6.5,则调用print函数输出格式为:(4.2,6.5)。主函数已给出,根据提示完成程序设计。
int main()
{
double r, m;
cin >> r >> m;
Complex c(r, m);
int n;
cin>>n;
Complex c1;
c1 = n+c;
Complex c2=c-n;
Complex c3=n-c;
c1.print();
c2.print();
c3.print();
return 0;
}
输入格式:
输入有两行,第1行为复数的实部与虚部 第2行为整数n
输出格式:
共3行输出,第1行为n+c1的结果,第2行为c1-n的结果,第3行为n-c1的结果。。
输入样例:
在这里给出一组输入。例如:
4.2 6.5
2
输出样例:
在这里给出相应的输出。例如:
(6.2,6.5)
(2.2,6.5)
(-2.2,-6.5)
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0, double i = 0) :real(r), imag(i)
{
}
friend Complex operator+(double n, Complex p);
friend Complex operator-( double n, Complex o);
friend Complex operator-(Complex o,double n);
void print() const;
private:
double real;
double imag;
};
Complex operator+(double n, Complex p) {
Complex c;
c.real = p.real + n;
c.imag = p.imag;
return c;
}
Complex operator-(Complex o, double n) {
Complex c;
c.real = o.real - n;
c.imag = o.imag ;
return c;
}
Complex operator-(double n, Complex o) {
Complex c;
c.real = n-o.real ;
c.imag = 0-o.imag;
return c;
}
void Complex::print() const
{
cout << "(" << real << "," << imag << ")" << endl;
}
int main()
{
double r, m;
cin >> r >> m;
Complex c(r, m);
int n;
cin >> n;
Complex c1;
c1 = n + c;
Complex c2 = c - n;
Complex c3 = n - c;
c1.print();
c2.print();
c3.print();
return 0;
}