C++ Primer 20120418

一:extern与const
@1:
1 extern int i;    //declare but don't define i
2 int i;            //declare and define i
@2:
1 extern int i; //声明
2 extern int i = 10; //虽然extern,但因为已包含对i的初始化,所以为定义,而不是声明
@3:
 1 //file1.c
 2 int counter; //definition
 3 //file2.c
 4 extern int counter;
 5 ++counter;
 6 
 7 //file1.c
 8 extern const int bufsize = fcn(); //用fcn()的返回值来初始化const变量bufsize OK
 9 //file2.c
10 extern const int bufsize;
11 for(int index = 0; index != bufsize; ++ index){
12  ...;
13 }
与其他变量不同,除非特别说明,在全局作用域声明的const变量是定义该对象的文件的局部变量。此变量只存在于那个文件中,不能被其他文件访问,除非显式的指定它为extern

@4:
非const变量默认为extern,所以可以在其他文件中通过extern声明而使用。要使const变量能够在其他文件中访问,必须显式的指定它为extern;

@5:
因为常量在定义后就不能被修改,所以const变量在定义时必须初始化
1 const std::string hi = “hello”;
2 const int i, j = 0; // error : i is uninitialized const


二:引用
@1:
引用必须用与该引用同类型的对象初始化,不能是具体的常数『除了const引用』
1 int ival = 1024;
2 int &refval1 = ival;
3 int &refval2; // error: a reference must be initialized
4 int &refval3 = 10; //error: initializer must be an object

@2:
当引用初始化后,只要该引用存在,它就保持绑定到初始化是指定的对象,不可将引用绑定到另一个对象。

@3:『IMPORTANT』
1 int i = 1024, i2 = 2048;
2 int &r = i, r2 = i2; //r is a reference, r2 is an int
3 int i3 = 1024, &ri = i3;
4 int &r3 = i3, &r4 = i2;

@4:const引用是指向const对象的引用,但const引用也可以指向非const对象『如下』,但此时不能通过ref来改变a
1  #include <iostream> 
2  using namespace std; 
3  int main(){ 
4   int a = 10; 
5   const int &ref = a; 
6   cout << ref << endl; 
7   return 0; 
8  }

const对象只能由const引用来引用,如:
1 const int a = 10;
2 const int &b = a; //OK
3 int &c = a; // error

@5:
 1 #include <iostream> 
 2  using namespace std; 
 3  int main(){ 
 4    double b = 2.022; 
 5    const int &ref1 = b;  //OK 
 6    cout << ref1 << endl; 
 7    double d = 2.33; 
 8    int &ref2 = d;      //ERROR
 9    cout << ref2 << endl;  
10    return 0; 
11  } 
const引用可以初始化为不同类型的对象,或者初始化为右值,但非const引用则不行,非const引用只能绑定到与该引用同类型的对象


三:一句话:
按接口编程,而不按实现编程,定义类时,通常先定义该类的接口,即该类所提供的操作。
原文地址:https://www.cnblogs.com/lxw0109/p/CPP_Primer_20120418.html