面向对象程序设计上机练习十(运算符重载)

面向对象程序设计上机练习十(运算符重载)

Time Limit: 1000MS  Memory Limit: 65536KB
Problem Description
定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。例如:c1+c2、i+c1、c1+i均合法。(其中i是整数,c1、c2是复数),编程实现求2个复数之和、整数与复数之和。
Input
输入有三行:第1行是第1个复数c1的实部和虚部,以空格分开。第2行是第2个复数c2的实部和虚部,以空格分开。第3行是1个整数i的值。
Output
输出有三行:
第1行是2个复数c1和c2的和,显示方式:实部+虚部i
第2行是第1个复数c1加i的值,显示方式:实部+虚部i 
第3行是i加第1个复数c1的值,显示方式:实部+虚部i
Example Input
2 3
3 5
10
Example Output
5+8i
12+3i
12+3i
本题的实现和无输入时对复数的操作是一样的,只不过是增加了输入。
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

class Complex{
private:
    double real, imag;
public:
    Complex(){real=imag=0;}
    Complex(double a, double b){
        real=a;
        imag=b;
    }
    Complex operator +(Complex &c);
    Complex operator -(Complex &c);
    void set_info(int a, int b){
    	real = a;
    	imag = b;
    }
    void display(){
        if(imag<0)
            cout<<real<<imag<<"i"<<endl;
        else
            cout<<real<<"+"<<imag<<"i"<<endl;
    }
};

inline Complex Complex::operator +(Complex &c){
    //return Complex(real+c.real, imag+c.imag);
    Complex temp;
    temp.real = this->real + c.real;
    temp.imag = this->imag + c.imag;
    return temp;
}

inline Complex Complex::operator -(Complex &c){
    return Complex(real-c.real, imag-c.imag);

}

int main(){
    Complex s[3];
    Complex t[3];
    int x, y;
    for(int i = 0; i < 2; i++){
    	 cin>>x>>y;
    	 s[i].set_info(x, y);
    }
    cin>>x;
    s[2].set_info(x, 0);
    t[0] = s[0] + s[1];
    t[1] = s[0] + s[2];
    t[2] = s[2] + s[0];
    for(int i = 0; i < 3; i++)
    	t[i].display();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值