2 头文件与类的声明

2 头文件与类的声明

我们的第一个 C++ 程序

  • Classes 的两个经典分类 :
    • Class without pointer member(s)
      complex
    • Class with pointer member(s)
      string

C++ 代码基本形式

.h (header files) 声明 + .cpp + .h (header files) 标准库

扩展名不一定是 .h 或 .cpp 也可能是 .hpp 或者其他甚至没有扩展名

<> 标准库

"" 自己写的头文件

基本的输出

#include <iostream.h>
using namespace std;

int main()
{
    int i = 7;
    cout << "i = " << i << endl;    // 把 c out 想象成你的屏幕, 向左的箭头就相当于把 i 往你的屏幕上丢

    return  0;
}

Header 头文件中的防御式声明

complex.h :

#ifndef __COMPLEX__
#define __COMPLEX__

/*
.....
*/

#endif

这是一种非常正规的头文件写法, 因为可能会有很多程序需要用到你的这个头文件, 第一次 include 的时候判断 ifndef 如果没有定义这个的话, 就定义 COMPLEX, 然后进入代码, 最后结束 if, 如果程序第二次 include 这个文件, 就不会进入代码, 这样就避免了重复的 include

头文件的布局

#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 的声明

// class head
class complex
// class body
// 有些函数在此直接定义, 另一些在 body 之外定义
{
    public:
        complex (double r = 0, double i = 0)
            :   re  (r), im (i)
        {}
        complex& operator += (const complex&);
        double real () const {return complex&}
        double imag () const {return im;}
    private:
        double re, im;

        friend complex& __doapl (complex*, const complex&);
};

{
    complex c1 (2, 1);
    complex c2;
    //...
}

class template (模板) 简介

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

我现在的需求是想把实部虚部的类型, 不要给它写死, 将来要用的时候再指定, 我就告诉编译器, 这里 re im 的类型是 T, T 只是一个符号, 告诉编译器我这里类型将来要用的时候再定义

{
    complex<double> c1 (2, 5, 1.5);
    complex<int> c2 (2, 6);
    //...
}

现在就是使用者终于要把这个实部虚部绑定为具体的类型了, 第一行就是指定为 double 这样这个 T 就被绑定为 double 了, 第二行同理就是绑定为 int