【c++笔记(一)侯捷老师课程】不带指针的类 ——复数的实现

一、头文件

#ifndef __COMPLEX__
#define __COMPLEX__           //防卫式声明

/****************前置声明**************/
class complex;
complex&
_doapl(complex* ths, const complex& r);

/****************类的声明**************/
class complex   
{
 public:
    complex(double r = 0, double i = 0): re(r), im(i){ }
	complex& operator +=(const complex&);
	double real() const { return re; }
	double imag() const { return im; }
 private:
 	double re, im;
    friend complex& _doapl(complex*, const complex&);
};  

/****************类的定义**************/
inline complex&
_doapl(complex* ths,complex& r)
{
	ths->re += r.re;
	ths->im += r.im;
	return *ths;
}

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

inline complex
operator + (const complex& x, const complex& y)
{
	return complex( real(x) + real(y), imag(x) + imag(y));
}

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());
}

inline complex&
operator - (complex& x)
{
	return complex(real(x), -imag(x));
}

inline complex&
operator + (complex& x)
{
	return x;
}

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


#endif

二、源文件

#include "complex.h"
#include<iostream>
using namespace std;
int main(){
	complex c1(1, 2);
	complex c2(3, 4);
	cout << c1 << endl;
	cout << c2 << endl;
	cout << "c1+c2=" << c1+c2 << endl;
	cout << "c1+=c2" << c1+=c2 << endl;
	cout << "-c1" << -c1 << endl;
	cout << "+c2" << +c2 << endl;
	cout << "5+c1" << 5+c1 << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值