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
Author
#include<bits/stdc++.h>
using namespace std;
class Complex
{
public:
Complex(double r = 0, double i = 0)
{
real = r;
image = i;
}
Complex operator+(Complex &c1);
Complex operator-(Complex &c1);
void display();
private:
double real, image;
};
Complex Complex::operator+(Complex &c1)
{
Complex c;
c.real = real + c1.real;
c.image = image + c1.image;
return c;
}
Complex Complex::operator-(Complex &c1)
{
Complex c;
c.real = real - c1.real;
c.image = image - c1.image;
return c;
}
void Complex::display()
{
cout<<real;
if(image > 0)
cout<<'+'<<image<<'i'<<endl;
else
cout<<image<<'i'<<endl;
}
int main()
{
Complex a(3.2,4.5);
Complex b(8.9,5.6);
Complex c3, c4;
c3 = a + b;
c4 = a - b;
cout<<"a=";a.display();
cout<<"b=";b.display();
cout<<"a+b=";c3.display();
cout<<"a-b=";c4.display();
return 0;
}
using namespace std;
class Complex
{
public:
Complex(double r = 0, double i = 0)
{
real = r;
image = i;
}
Complex operator+(Complex &c1);
Complex operator-(Complex &c1);
void display();
private:
double real, image;
};
Complex Complex::operator+(Complex &c1)
{
Complex c;
c.real = real + c1.real;
c.image = image + c1.image;
return c;
}
Complex Complex::operator-(Complex &c1)
{
Complex c;
c.real = real - c1.real;
c.image = image - c1.image;
return c;
}
void Complex::display()
{
cout<<real;
if(image > 0)
cout<<'+'<<image<<'i'<<endl;
else
cout<<image<<'i'<<endl;
}
int main()
{
Complex a(3.2,4.5);
Complex b(8.9,5.6);
Complex c3, c4;
c3 = a + b;
c4 = a - b;
cout<<"a=";a.display();
cout<<"b=";b.display();
cout<<"a+b=";c3.display();
cout<<"a-b=";c4.display();
return 0;
}