C++类声明定义“复数”的抽象数据类型(+ - * / <<运算符重载)

#include<iostream>
using namespace std;
class complex
{
	double t, n;     //t为实部 n为虚部
public:
	complex(double T = 0, double N = 0) : t(T), n(N) {}     //初值为0构造函数
	~complex() { }
	double getT() { return t; }
	double getN() { return n; }
	complex operator+(const complex& a) {         //+重载
		complex b;
		b.t = t + a.t;
		b.n = n + a.n;
		return b;
	}
	complex operator-(const complex& a) {         //-重载
		complex b;
		b.t = t - a.t;
		b.n = n - a.n;
		return b;
	}
	complex operator*(const complex& a) {         //*重载
		complex b;
		b.t = t * a.t;
		b.n = n * a.n;
		return b;
	}	complex operator/(const complex& a) {      //‘/’重载
		complex b;
		b.t = (t * a.t + n * a.n) / (a.t * a.t + a.n * a.n);
		b.n = (-t * a.n + n * a.t) / (a.n * a.n + a.t * a.t);
		return b;
	}
	friend ostream& operator<<(ostream& cout, complex& p);
};
ostream& operator<<(ostream& c, complex& p) {           //<<重载
    c<< p.t ;
	if (p.n > 0)return c<< "+" << p.n<<"i";
	else if(p.n < 0)return c<< p.n<<"i";
}

int main()
{
	double x, y, z, w;
	cin >> x >> y >> z >> w;
	complex a(x, y), b(z, w), c;
	c = a + b; cout << c << endl;
	c = a - b; cout << c << endl;
	c = a * b; cout << c << endl;
	c = a / b; cout << c << endl;
	return 0;
}

重载左移运算符时返回值类型为ostream&,之后可以对返回的值连续操作。

重载左移运算符也可为:

ostream& operator<<(ostream& cout, complex& p) {           //<<重载
    cout<< p.t ;
	if (p.n > 0)return cout<< "+" << p.n<<"i";
	else if(p.n < 0)return cout<< p.n<<"i";
}

若传入为ostream& c(c实际是cout的别称),则函数中c、cout可混用;

传入为ostream& cout,函数体中不能用别称。

菜鸡代码,评论(如果有)大佬说的都对/doge

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值