文章目录
  1. 1. 声明和定义
  2. 2. inline、内联函数及成员函数写在类定义内部和外部的区别
  3. 3. explicit、implicit

声明和定义

  1. 不需要分配空间的为声明(declaration),需要分配的为定义(definition),前者又称为定义性声明,后者为引用性声明。声明是告诉编译器哪里可以找到该符号。
  2. 在一个作用域中可以重复声明,但不能重复定义。可以重复几次告诉编译器某个变量、函数已经在别处定义了,但不能重复多次地让编译器为同一个变量、函数分配不同的存储空间。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    //声明
    extern int c;
    double sqrt(double x);
    extern int g(int, int);
    class foo;
    struct S;
    typedef long LONG_32;
    using namespace std; // 声明std
    class foo{ // 定义
    static int a; // 声明静态成员变量(赋值为定义)
    };
    extern "C" { ... }
    using IntVector = std::vector<int>; // c11
    enum X : int; // c11
    template <class T> class C; // c11
    ; // c11

    //定义
    extern const int c = 1;
    double sqrt(double x){ return x * x; } // 定义sqrt和x
    int a;
    int b = 0;
    class foo {};
    struct S { int a; int b; }; // 定义S,a和b
    static int a;
    enum { up , down }; // 定义up和down

    ref:
    stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration

inline、内联函数及成员函数写在类定义内部和外部的区别

内联函数指编译器编译时采用类似宏替换的操作将函数体嵌入每一个调用处,使得调用时不发生控制权转移(保存状态,压栈出栈,跳转等)

  1. 编译器根据情况决定哪些函数为内联函数
  2. 用inline标识函数为内联函数,但是否编译为内联函数由编译器决定。
  3. 写在类定义内的成员函数默认添加inline标识,但在类定义外的成员函数不会自动添加inline标识。
  4. inline仅在类定义时生效
    1
    2
    3
    4
    5
    class foo{
    int f(int a){ return a + 1;} // 前面自动添加inline
    };
    int foo::g(int b){ return b + 1; } // 前面不自动添加inline
    inline int foo::bar(int c){ return c + 1; } // 手动添加inline

explicit、implicit

文章目录
  1. 1. 声明和定义
  2. 2. inline、内联函数及成员函数写在类定义内部和外部的区别
  3. 3. explicit、implicit