C++简易复数类的实现

两个反思点:
在使用流运算符时需要使用友元函数。
在实战中,运算符的重载若为成员函数其参数必须少于2两个,即最多一个参数。所以流运算符需要有两个参数,但是它又必须调用类里的私有成员,所以就使用了友元函数的方法。
其余都是比较easy的。

#include <iostream>
using namespace std;

class Complex
{
private:
  	double real;
  	double image;
public:
  	Complex(const Complex& complex) :real{ complex.real }, image{ complex.image } {
  	}
  	Complex(double Real=0, double Image=0) :real{ Real }, image{ Image } {
  	}
    Complex operator=(const Complex& a);
    Complex operator+(const Complex& a);
    Complex operator-(const Complex& a);
    Complex operator*(const Complex& a);
    Complex operator/(const Complex& a);
    friend ostream& operator<<(ostream &out, const Complex &a);
    friend istream& operator>>(istream &in, Complex &a);
};
Complex Complex::operator+(const Complex &b)
{
    return Complex(real + b.real, image + b.image);
    }
	Complex Complex::operator-(const Complex& b){
        return Complex(real-b.real, image-b.image);
    }
	Complex Complex::operator*(const Complex& b){
        return Complex(real*b.real-image*b.image, real*b.image+image*b.real);
    }
	Complex Complex::operator/(const Complex& b){
        Complex temp(real, image);
        int dom = b.real * b.real + b.image * b.image;
        Complex son = Complex(b.real/dom, -b.image/dom);
        return Complex(temp*son);
    }
    ostream& operator<<(ostream &out, const Complex &a){
        if(a.image>=0){
            return out << "(" << a.real << "+" << a.image << "i)" ;
        }else{
            return out << "(" << a.real  << a.image << "i)" ;
        }
    }
    istream& operator>>(istream &in, Complex &a){
        return in >> a.real >> a.image;
    }

    int main()
    {
        Complex z1, z2;
        cin >> z1;
        cin >> z2;
        cout << z1 << " " << z2 << endl;
        cout << z1 + z2 << endl;
        cout << z1 - z2 << endl;
        cout << z1 * z2 << endl;
        cout << z1 / z2 << endl;
        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值