#include <bits/stdc++.h>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex(double a = 0,double b = 0)//构造函数
{
real = a;
imag = b;
}
friend ostream &operator<<(ostream &,Complex &);//友元运算符重载声明
Complex operator+(Complex &);
Complex operator-(Complex &); //普通运算符重载声明
};
Complex Complex::operator+(Complex &c1)
{
Complex c;
c.real = c1.real + real;
c.imag = c1.imag + imag;
return c;
}
Complex Complex::operator-(Complex &c1)
{
Complex c;
c.real = real - c1.real;
c.imag = imag - c1.imag;
return c;
}
ostream &operator<<(ostream & output,Complex &c)//类外部写函数时,友元函数不加friend
{
output<<c.real;
if(c.imag != 0)
{
if(c.imag > 0)
{
output<<"+";
}
}
output<<c.imag<<"i";
return output;
}
int main()
{
Complex a(3.2,4.5),b(8.9,5.6);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
Complex c;
c = a + b;
cout<<"a+b="<<c<<endl;
c = a - b;
cout<<"a-b="<<c<<endl;
return 0;
}
4-1 复数类的运算符重载--成员运算符重载、友元运算符重载
最新推荐文章于 2019-11-26 23:13:57 发布
本文介绍了一个简单的C++程序,用于实现复数类的定义、基本运算(加法和减法),以及如何通过重载运算符来实现复数的输入输出。程序展示了如何创建复数对象,并进行加减运算。
1471

被折叠的 条评论
为什么被折叠?



