2.头文件与类的声明

1.创建头文件的时候加入防御式声明

ifndef A

define A

endif

2.非模板,这里需要前置声明

ifndef COMPLEX

define COMPLEX

include

/* 前置声明 */
class ostream;
class complex;

complex&
__doapl (complex* ths, const complex& r);
/* 它接收“当前对象”(ths)和“要加上的对象”(r),把 r 加到当前对象上,然后返回当前对象的引用。 */

/* 类声明 /
class complex /
class head /
{/
class body */
public:
complex (double r = 0, double i = 0)// 构造函数
: re (r), im (i)// 初始化列表:把参数 r 给 re,i 给 im
{ }// 函数体为空,因为初始化列表已经做完事了

complex& operator += (const complex&);// 声明 operator += 成员函数
double real () const {return re; }//取实部函数,加 const 表示不修改对象
double imag () const {return im; }// 取虚部函数

private:
double re, im;// 复数的两个成员变量:实部 re,虚部 im
// 声明一个友元函数__doapl 允许这个外部函数直接访问 private 的 re、im
friend complex& __doap1 (complex*, const complex&);
};

/* 头声明 */

endif

3.模板,template这里的T可以变换数据类型

ifndef COMPLEX

define COMPLEX

include

/* 前置声明 */

/* 类声明 /
template
class complex /
class head /
{/
class body */
public:
complex (T r = 0, T i = 0)
: re (r), im (i)
{ }
complex& operator += (const complex&);
T real () const {return re; }
T imag () const {return im; }
private:
T re, im;

friend complex& __doap1 (complex*, const complex&);

};

/* 用法 */
complex c1(2.5, 1.5);
complex c2(2, 6);

/* 头声明 */

endif

posted @ 2026-01-06 14:47  r5ett  阅读(3)  评论(0)    收藏  举报