C++学习笔记(三)

C++学习笔记

提示:本笔记是个人学习侯捷C++课程的总结笔记,欢迎来信批评指正!
第一篇 C++基础以及编程规范(一)
第二篇 运算符重载
第三篇 规范编写复数类



提示:以下是本篇文章正文内容,下面案例可供参考

写个复数类示例

/*防卫式声明,回见第一篇*/
#ifndef __COMPLEX__
#define __COMPLEX__

class complex
{
public:
	/*构造函数,使用初值列,回见第一篇*/
	complex (double r=0,double i=0)
		:re(r),im(i)
	{	}	/*本示例除了构造初值,无需其他操作*/
	/*设计一个成员函数+=,该处只是声明*/
	complex& operator += (const complex&);
	/*定义成员函数,分别取该复数的实部和虚部,无需改动data,故加上const*/
	double real () const {return re;}
	double imag () const {return im;}
private:
	double re,im;
	/*友元函数,直接取data*/
	friend complex& __doapl(complex*,const complex&);
};

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

/*左边加右边,结果需要一个local临时对象*/
/*复数加复数*/
inline complex
operator + (const complex& x,const complex& y)
{
	return complex(real(x) + real(y)imag(x)+imag(y)	);
}
/*复数加doule*/
inline complex operator + (const complex& x,double y)
{
	return complex(real(x)+y,imag(x));
}
/*double加复数*/
inline complex operator + (double x,const complex& y)
{
	return complex(x+real(y),imag(y));
}

<<操作符特殊,因为写成成员函数其第一个形参必定是complex类型,那就是c1<<cout;其与表达习惯不符,故使用非成员函数编写。

#include <iostream.h>
/*cout是输出流ostream类型,可以引用传递,且会改变,故非const*/
/*c1是complex类型,可以引用传递,不会改变原值,故为const*/
ostream&
operator << (ostream& os,const complex& x)
{
	return os<<'('<<real(x)<<','<<imag(x)<<')';
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值