侯捷-C++面向对象高级开发(上) 笔记06 complex的简易实现

complex.h头文件

#pragma once
#ifndef __COMPLEX__
#define __COMPLEX__

#include <iostream>
#include <ostream>

class complex
{
public:
	complex(double re = 0, double im = 0)
		: rel(re)   , ima(im)           //初始行和初始列
	{}

	complex(const complex & com)  //拷贝构造函数
	{
		rel = com.rel;
		ima = com.ima;
	}

	double get_rel() const { return rel; }
	double get_ima() const { return ima; }

	//重载操作符+=,实现复数相加 和 复数加实数

	complex & operator +=(const complex com)
	{
		rel += com.rel;
		ima += com.ima;
		return *this;
	}

	complex & operator +=(const double tmp)
	{
		rel += tmp;
		return *this;
	}

private:

	double rel;
	double ima;
};

//重载操作符<<,不能是成员函数重载
//因为如果是成员函数重载<< ,则cout<<re ,本质上是cout.operator<<(re)
//而cout属于iostram标准库,是不允许添加和修改的
//而re<<cout ,又不符合常规用法

inline 
std :: ostream & operator<<(std :: ostream & os, const complex com) //返回引用是因为可能cout<<re<<im;连续使用,
{                                                                   //os是引用是因为os属于输出内容,缓冲区需要被修改
	return os << com.get_rel() << " + "<<com.get_ima() << "i" ;     //os在()里位于左边,是因为cout<<re; cout在左                                                                   
}                                                                   //非成员函数重载操作符严格遵守这样的顺序,一一对应

//重载操作符 +,
inline 
complex  operator +(const complex & a, const complex & b)
{
	return complex(a.get_rel() + b.get_rel(), a.get_ima() + b.get_ima());
}

inline 
complex operator + (const complex & a, const double & b)
{
	return complex(a.get_rel() + b, a.get_ima());
}

inline 
complex operator + (const double  a, const complex &b)
{
	return complex(a + b.get_rel(), b.get_ima());
}

//重载正负号
inline complex operator + (const complex& x) {
	return x;
}

inline complex operator - (const complex& x) {
	return complex(-x.get_rel(), -x.get_ima());
}
#endif // !__COMPLEX__

测试文件complex_test.cpp

#include<iostream>
#include"complex.h"

using namespace std;

int main()
{
	complex a;
	cout << a << endl;

	complex b(1, 1);

	cout << a + b << endl;
	a += b += b;
	cout << a << endl;
	cout << a <<"  "<< b << endl;

	complex c(b);
	cout << c << endl;
	cout << +c << endl;
	cout << -c << endl;

	cout << c + 3 << endl;
	cout << 3 + c << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值