c++中复数实现分析

Complex.h

/*  防止代码被重复编译  */
#ifndef __COMPLEX__
#define __COMPLEX__

#include 

class Complex
{
public:
	 /* 
	 	1. 优先选择使用初始化列表 
	 	2. 可以传递引用,由于double和指针的大小相同,所以两种方式在此处无区别
	 	3. 默认参数是为了Complex c、Complex c(1)两种定义形式
	 */
	Complex(double r = 0, double i = 0)
		:re(r), im(i)
	{
	
	}
	
	/*
		1.传参引用减少传递大小压力,32位机传递引用(4字节),传值(8字节)
		2. 类成员函数默认第一个参数是类对象指针(this),所以只需要显示传递一个参数
		3. 不会修改右值,使用const修饰
		4. 为了实现c3 += c2 += c1,必须有返回
	*/
	Complex &operator += (const Complex &r);
	
	/* 
		1. 不会改变成员变量的值,所以使用const修饰
		2. 在类内部实现,默认为inline函数
	 */
	double real() const 
	{
		return re;
	}
	double imag() const
	{
		return im;
	}

private:
	double re;
	double im;
	
	/*  通过友元,全局函数可以通过类对象的访问私有成员  */
	friend Complex& __doapl(Complex *, const Complex &); 
	friend ostream & operator << (ostream & os, const Complex &x);
};

#endif 

Complex.cpp

/* 类外实现,并且函数比较简单短小,所以使用inline */
inline Complex&  __doapl(Complex *ts, const Complex &r)
{
	ts->re += r.re;
	ts->im += r.im;

	return *ts;
}

inline Complex &Complex::operator += (const Complex &r)
{
	return __doapl(this, r);
}

/*   设计为全局函数,为了实现重载,应付多种参数变化情况   */
inline Complex operator + (const Complex& x, const Complex& y)
{
	/* 返回一个临时对象,只在当前行有效  */
	return Complex(x.real() + y.real(), x.imag() + y.imag());
}
inline Complex operator + (const Complex& x, const double& y)
{
	return Complex(x.real() + y, x.imag() );
}
inline Complex operator + (const double& x, const Complex& y)
{
	return Complex(x + y.real(), y.imag());
}

/*
	例:cout << c << endl;
	1. 为了连续输出所以返回ostream
	2. cout是全局对象,所以可以返回引用
	3. 在输出打印时,cout的状态是一直在发生改变,所以传参时不能使用const修饰
*/
ostream & operator << (ostream & os, const Complex &x)
{
	return os << ‘(’ << x.real() << ',' << x.imag() << ')';
}

你可能感兴趣的:(c++)