代码改变世界

C++Primer学习笔记(二、基础)

2014-02-16 11:10  阿普的博客  阅读(148)  评论(0编辑  收藏  举报

1、两种初始化方式,直接初始化语法更灵活,且效率更高。

int ival(1024);     // 直接初始化 direct-initialization
int ival = 1024;    // 赋值初始化 copy-initialization

2、const变量与一般变量的不同

//一般变量的用法
// file_1.cc
int counter;  // 在file_1.cc中定义
// file_2.cc
extern int counter; // 在file_2.cc中使用
++counter;          
//const变量用法
// file_1.cc
extern const int bufSize = fcn(); //在file_1.cc中定义,需要有extern修饰
// file_2.cc
extern const int bufSize; // 在file_2.cc中使用

3、引用

//一般引用
int ival = 1024;
int &refVal = ival;  // refVal引用ival,要求ival与refVal类型一致
// const 引用
const int &refval=3; //静态引用可以直接以赋值

double dval = 3.14;
const int &refval2=dval; // 静态引用可以使变量类型不同,赋值时,会将dval转换为                                        int类型,然后赋值,结果为3    

4、枚举

enum Points { point2d = 2, point2w,point3d = 3, point3w };

// 赋值
Points pt3d = point3d; //  ok: point3d is a Points enumerator
Points pt2w = 3;       //  error: pt2w initialized with int
pt2w = polygon;        //  error: polygon is not a Points enumerator
pt2w = pt3d;           //  ok: both are objects of Points enum type

5、class 、struct

用 class 和 struct 关键字定义类的唯一差别在于默认访问级别:默认情况下,struct 的成员为 public,而 class 的成员为 private

6、头文件

因为头文件包含在多个源文件中,所以不应该含有变量或函数的定义。