1. 数据类型
1.1 基本内置类型
我们通过下列代码可知电脑上的基本数据类型的大小:
1 #include<iostream> 2 #include<string> 3 #include <limits> 4 using namespace std; 5 6 int main() 7 { 8 9 cout << "char: \t\t" << "所占字节数:" << sizeof(char); 10 cout << "\t最大值:" << (numeric_limits<char>::max)(); 11 cout << "\t\t最小值:" << (numeric_limits<char>::min)() << endl; 12 13 cout << "float: \t\t" << "所占字节数:" << sizeof(float); 14 cout << "\t最大值:" << (numeric_limits<float>::max)(); 15 cout << "\t\t最小值:" << (numeric_limits<float>::min)() << endl; 16 17 cout << "int: \t\t" << "所占字节数:" << sizeof(int); 18 cout << "\t最大值:" << (numeric_limits<int>::max)(); 19 cout << "\t最小值:" << (numeric_limits<int>::min)() << endl; 20 21 cout << "unsigned: \t" << "所占字节数:" << sizeof(unsigned); 22 cout << "\t最大值:" << (numeric_limits<unsigned>::max)(); 23 cout << "\t最小值:" << (numeric_limits<unsigned>::min)() << endl; 24 25 cout << "long: \t\t" << "所占字节数:" << sizeof(long); 26 cout << "\t最大值:" << (numeric_limits<long>::max)(); 27 cout << "\t最小值:" << (numeric_limits<long>::min)() << endl; 28 29 30 cout << "double: \t" << "所占字节数:" << sizeof(double); 31 cout << "\t最大值:" << (numeric_limits<double>::max)(); 32 cout << "\t最小值:" << (numeric_limits<double>::min)() << endl; 33 return 0; 34 }
1.2 const 和 auto
1. const 基本介绍
const对象一旦创建后其值就不能再改变,所以const对象必须初始化。编译器在编译过程会把用到该变量的地方替换成相应的值,为了执行上述的替换,编译器必须知道变量的初始值。
1 const int i = get_size(); // 运行时初始化 2 const int j = 3; // 编译时初始化 3 const int k;// 错误
默认情况下,const对象仅在文件中有效。当多个文件中出现了同名的const变量时,其实等同于在不同文件中分别定义了独立的变量。如果想在在文件中得到共享,即在一个文件中定义const,而在其他多个文件中声明并使用它。可以使用 extern 关键词,对于const变量不管是声明还是定义都添加 extern 关键词,这样只需定义一次就可以了。
但是需要注意下面这个例子:
1 struct A { 2 int* ptr; 3 }; 4 5 int main() 6 { 7 int k = 5, r = 6; 8 const A a = { &k };// const声明的变量必须初始化 9 a.ptr = &r; // !error 10 *a.ptr = 7; // no error 11 }
可以看到,const 修饰 a 之后其实要求的是 ptr (存储一个地址)不能变,但其实可以改变 *ptr—— c++ 保持物理常量行不变,逻辑常量性不保证。
2. 类中的const变量
1 struct A { 2 const int i; // 构造类是初始化。非静态 3 }; 4 5 struct B { 6 static const int i;// 静态 7 }; 8 9 const int B::i = 3; // 常在类中中直接声明 10 11 int main() 12 { 13 A bf = { 1 }; 14 15 }
3. 顶/底层 const 和 auto
下面是顶层 const 和 底层 const 的实例:
1 /* 2 ① 3 顶层const:指针本身是个常量 4 底层const:指针所指的对象是一个常量 5 6 ② 7 auto一般会忽略顶层const,会保留底层const 8 */ 9 10 #include"iostream" 11 using namespace std; 12 int main() 13 { 14 const int i = 19; //i值不能改变,顶层const 15 const int *p = &i;//p值可以改变,底层const(*P值不能改变->指针所指的对象是个常量) 16 17 int z = 18; 18 int *const o = &z;//o值不能改变,顶层const 19 int t = 13; 20 //o = &t; //错误,因为o是顶层,o值不能改变 21 22 //打印类型 23 cout << typeid(i).name() << endl;//int 24 cou