GeekBand笔记: C++面向对象高级编程(1)

2016-02-28  本文已影响0人  Royye

面向对象 Object Oritented

基于对象(Object Based) vs. 面向对象(Object Oritented)

面向对象编程的特性 features of OOP (A PIE)

对象的构成 an object consist of

C++ Class 的两种经典分类

重要概念梳理


1. const 关键字

C++中的const关键字的用法非常灵活,而使用const将大大改善程序的健壮性。

初始化和const

普通变量和const

const int n = 10;
n是一个只读变量,程序不可以直接修改其值。这里还有一个问题需要注意,即如下使用:int a[n];在ANSI C中,这种写法是错误的,因为数组的大小应该是个常量,而n只是一个变量。

注:看到const关键字,很多人想到的可能是const常量,其实关键字const并不能把变量变成常量!在一个符号前加上const限定符只是表示这个符号不能被赋值。也就是它的值对于这个符号来说是只读的,但它并不能防止通过程序的内部(甚至是外部)的方法来修改这个值(C专家编程.p21)。也就是说 const变量是只读变量,既然是变量那么就可以取得其地址,然后修改其值。看来const也是防君子不防小人啊!:)

指针和const

诀窍:沿着号划一条线,如果const位于的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;如果const位于*的右侧,const就是修饰指针本身,即指针本身是常量。

顶层const和底层const

    - const int i = 10;
    - char * const p = NULL;
    - const int *p2 = NULL;
    - const int &r = i;

cosnt对象拷贝

    void func(const int i) // 既可以传const int,也可以传int
    int i = 42;
    const ci = 32;
    const int *cp = &ci; // OK. 底层const类型匹配
    const int *cp = &i; // OK. int * 能转换成 const int *
    int * p = cp; // Error, 底层const类型不匹配,const int * 不能转换成 int *
    int &r = ci;  // Error, 底层const类型不匹配,int引用不能绑定到int常量上
    void func(int *p);
    func(&i); // OK.
    func(cp); // Error. const int * 不能转换成 int *

类和const

constexpr 和 const expression(常量表达式)

    - const int max = 20; // 字面值一定是常量表达式
    - int max = 20; //不是。非const int
    - const max = get_max(); // 不是。get_max运行时知道结果

const定义常量 代替 常量宏


2. inline vs. marco

相同点

消除函数调用的开销(参数压栈、跳转、弹栈、返回等指令操作)

不同点

注意

上一篇 下一篇

猜你喜欢

热点阅读