C++——Const总结

来源:互联网 发布:淘宝助理是免费的吗 编辑:程序博客网 时间:2024/06/06 16:39

作用域

默认const定义在函数外,则作用域仅在文件内有效
如果希望扩大作用域,则需要在变量定义和声明之前添加 extern关键字。

// file_1.cpp

extern const int maxValue = 1024;

// file_1.h

extern const int maxValue;

特征

当以编译时初始化的方式定义一个const对象时,如下面所示

const int maxValue = 1024; 

因为是通过常量表达式初始化,所以编译器在编译的时候会把使用该变量的地方替换成对应的值。代码中所有使用maxValue的地方都会被替换成1024。

可以通过指针来改变const 局部变量的值

不过要注意
const不能是常量表达式。也就是说,不能在编译阶段计算出来。因为常量表达式的const会在编译阶段直接将使用该const常量表达式的地方替换成const所代表的常量(如上面的maxValue常量)。也就是说在运行阶段改变了const局部变量的值,并不会影响使用const常量的语句。因为这些使用const常量的地方,在编译阶段就已经被替换为相应的常量表达式。
成功改变const局部变量的例子

#include <iostream>using namespace std;int fun(){    return 1;}int main() {    const int a = fun();//使得const变量需要在运行阶段才能计算出来。    int* b = (int *)&a;    *b = 31;    cout << a << endl;    return 0;}

输出结果为

31

但是非局部const变量则会出现段错误:

#include <iostream>using namespace std;int fun(){    return 1;}const int a = 23;int main() {    //const int a = fun();    int* b = (int *)&a;    *b = 31;    cout << a << endl;    return 0;}

输出以下错误,也就是有代码修改了不能修改内存区域

[1]    18284 segmentation fault  ./CppLearn
0 0
原创粉丝点击