4-1 复数类的运算符重载
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
通过本题目的练习可以掌握成员运算符重载及友元运算符重载
要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。
Input
要求在主函数中创建对象时初始化对象的值。
Output
输出数据共有4行,分别代表a,b的值和它们求和、求差后的值
Example Input
无
Example Output
a=3.2+4.5i b=8.9+5.6i a+b=12.1+10.1i a-b=-5.7-1.1i
Hint
#include<bits/stdc++.h>
using namespace std;
class Complex
{
private:
double real, imag;
public:
Complex(double r = 0.0, double i = 0.0)
{
real = r;
imag = i;
}
void showComplex()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
void show()
{
cout<<real<<imag<<"i"<<endl;
}
Complex operator+ (Complex &b);
Complex operator- (Complex &b);
};
Complex Complex::operator+(Complex &b)
{
return Complex(real+b.real, imag + b.imag);
}
Complex Complex::operator-(Complex &b)
{
return Complex(real - b.real, imag - b.imag);
}
int main()
{
Complex a(3.2, 4.5);
cout<<"a=";a.showComplex();
Complex b(8.9, 5.6);
cout<<"b=";b.showComplex();
Complex c = a + b;
cout<<"a+b=";c.showComplex();
c = a - b;
cout<<"a-b=";c.show();
return 0;
}
或者
#include<iostream>
using namespace std;
class yunsuan
{
public :
yunsuan(double r=0,double i=0)
{
real=r;
image=i;
}
yunsuan operator +(yunsuan &c2)
{
yunsuan c;
c.real=real+c2.real;
c.image=image+c2.image;
return c;
}
yunsuan operator -(yunsuan &c2)
{
yunsuan c;
c.real=real-c2.real;
c.image=image-c2.image;
return c;
}
void display ()
{
cout<<real;
if(image>0)
{
cout<<"+";
}
cout<<image<<"i";
}
private:
double real,image;
};
int main()
{
yunsuan c1(3.2,4.5),c2(8.9,5.6),c3;
cout<<"a=";
c1.display();
cout<<endl;
cout<<"b=";
c2.display();
cout<<endl;
c3=c1+c2;
cout<<"a+b=";
c3.display();
c3=c1-c2;
cout<<endl;
cout<<"a-b=";
c3.display();
cout<<endl;
return 0;
}