我们在开始学习C++时,就应该养成规范大气的编程习惯,头文件(header)的布局就是其中很重要的一个点。我们需要知道头文件中的防卫式声明。
#ifndef __COMPLEX__ #define __COMPLEX__ //前置声明(forward declarations) #include<cmath> class ostream; class complex; complex& __doapl (complex* ths, const complex& r); //类-声明(class-declarations) class complex { ... }; //类-定义(class-definition) complex::function ... #endif
在类的声明部分,我们来看看规范的格式是怎样的,可以为我们以后的编程风格打下基础。
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&); };
类的声明中包括class head和class body两部分,有些函数直接在body内定义,比如这里的real()、imag(),还有一些在body之外定义。
在C++中模板(template)也很重要,如果我们不希望把数据类型double写死,这样很不方便我们修改。我们就可以用到模板。
template<typename T> class complex { 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& __doapl (complex*, const complex&); };
C++中的内联函数(inline function)可以取代表达式形式的宏定义,如果函数在class body内定义完成,不需要加inline关键字修饰,便自动成为inline候选人。但在类外定义函数前就需要添加inline修饰,inline对编译器来说只是一种建议,编译器可以选择忽略这个建议。比如,将一个长达1000多行的函数指定为inline,编译器就会忽略这个inline,将这个函数还原成普通函数。我们需要知道,内联函数是在编译时将该函数的目标代码插入到每个调用该函数的地方。
关于访问级别(access level)有public,private和protected三种,我们一般将函数放在public区,将数据放在private区。访问级别是可以交错使用的。