定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的可以都是类对象,也可以其中一个是整数,顺序任意。分别求两个复数之和、 整数和复数之和,复数的输入和输出重载>>和<<

#include<iostream>
using namespace std;
class complex
{
public:
    complex() :real(0), imag(0) {};
    complex(float a,float b):real(a), imag(b) {};
    complex operator+(complex&);
    friend complex  operator+(int i, complex&);
    friend complex  operator+(complex&, int i);
    friend istream& operator>>(istream&, complex&);
    friend ostream& operator<<(ostream&, complex&);
private:
    float real;
    float imag;
};
complex complex::operator+(complex& c2)
{
    complex c;
    c.real = real + c2.real;
    c.imag = imag + c2.imag;
    return c;
}
complex  operator+(int i, complex&c2)
{
    complex c;
    c.real = c2.real + i;
    c.imag = c2.imag;
    return c;
}
complex  operator+(complex& c2, int i)
{
    complex c;
    c.real = c2.real + i;
    c.imag = c2.imag;
    return c;
}
istream& operator>>(istream&input,complex &c)
{
    float a, b;char s,d;
    input >> c.real >> s >> c.imag>>d;
    if (s == '-')c.imag -= 2 * c.imag;
    return input;
}
ostream& operator<<(ostream& output, complex& c)
{
    output << c.real << "+" << c.imag << "i";
    return output;
}
int main()
{
    complex c1, c2;int n;
    complex c3, c4, c5;
    cout << "请输入第一个复数c1:";cin >>c1;
    cout << "请输入第二个复数c2:";cin >> c2;
    cout << "请输入一个整数n:";cin >> n;
    c3 = c1 + c2;c4 = c1 + n;c5 = n + c2;cout << "c1+c2、c1+n、n+c2分别为:\n";
    cout << c3 << "\t" << c4 << "\t" << c5;
}

运行结果如下:

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值