cpp_go_hdc_review1

#ifndef __COMPLEX__
#define __COMPLEX__

class complex
{
public:
	complex(double r = 0, double i = 0)	//pass by value
		: re(r), im(i)			//initialization list
	{  }
	complex& operator + =const complex&);		//member function
	double real() { return re; }
	double imag() { return im; }


private:
	double re, im;

	friend complex& __doapl(complex*,			//do assignment plus
							const complex&);
};

#endif
inline	complex&			// return type
__doapl(complex* ths, const complex& r)
{
	ths->re += r.re;
	ths->im += r.im;
	return *ths;
}


inline complex&
complex::operator + = (const complex& r)		//member function
{
	return __doapl(this, r);
}

inline	complex				//return by value
operator + (const complex& x, const complex& y)
{
	return complex ( real (x) + real (y),
					 imag (x) + imag (y) );			//temporary object
}
inline complex
operator + (const complex& x, double y)
{
	return complex(real(x) + y, imag(x));
}
inline complex
operator + (double x, const complex& y)
{
	return complex(x + real(y), imag(y));
}

#include <iostream>
ostream&					//
operator << (ostream& os,
	const complex& x)				//overloading
{
	return os << '(' << real(x) << ','
		<< imag(x) << ')';
}

类内:

  1. 防卫式的常数定义
  2. 设计一个复数 写出class头
  3. 考虑复数要存放的数据,放于private中(实部虚部),并考虑实部虚部的数据类型(double)
  4. 考虑有哪些函数操作于复数上(每一个class都要去想它的构造函数),考虑其是否需要默认值,考虑其传递方式是pass by reference or pass by value
  5. 构造函数特殊语法:initialization list(初值列)即设初值
  6. 作为一个复数设计者,思考该复数类具有什么能力并设计
    (1)设计+=
    (2)设计取得实部和取得虚部 --思考会不会改动re im数据
  7. 为了取得私有的实部虚部的数据,在class中声明friend函数

类的本体外:

  1. +=的操作符重载(思考其参数)
  2. 考虑它的return type,所传出去的如果不是函数本体内创建的就可以引用
  3. 定义部分:把+=丢给新定义的函数去做,也将收到的参数往下一步操作的函数传递
  4. 根据收到的参数类型确定新定义函数的参数类型
  5. 考虑return type,使其成为inline
  6. 函数体内设计+=:右边的参数加到左边的参数上 (由此可以看出右边参数为不可变的const类型),返回指针参数
  7. 设计全局函数(无类的名称),传递两个常量
  8. 创建一个新的对象用于放置 左常量+右常量:类的名称后加( )即创建新object
  9. 考虑到复数的不同加法类型
  10. 把复数输出设为cout(操作符重载) 》cout<<c1 (c1丢给左边参数)
  11. 返回ostream 参数的引用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值