回顾 设计一个class需要注意:
- 构造函数中对参数使用 冒号 : 初始化
- 成员函数该不该加const,如果不加可能有什么副作用?
- 传参数尽量 pass by reference,加不加const?
- 返回的时候 return by what?const or not
- 数据一般放在 private,函数一般 public
头文件
#ifndef __COMPLEX__ // 1.防卫式声明
#define __COMPLEX__
#include <iostream>
using std::ostream;
// 2.class head
class complex
{ // class body
public:
// 3.构造函数 inline
complex (double r = 0, double i = 0) // pass by 什么都可以,因为double是4个字节
: re(r), im(i) // 设初值
{ }
// 有些函数在此直接定义,另一些在body之外定义
complex& operator += (const complex&); // 5.重载+=,设计为成员函数
// 4.取得实部和虚部,不会改data,所以函数是const;inline
double real() const { return re; }
double imag() const { return im; }
private:
double re, im;
// 6.do assignment-plus 函数中想直接取得re和im,所以声明成友元函数
friend complex& __doapl(complex*, const complex&);
};
#endif // __COMPLEX__
cpp文件
#include "complex.h"