C++中的const用法

来源:互联网 发布:彩虹六号最低配优化 编辑:程序博客网 时间:2024/05/16 06:00

C++中的const限定符可比C语言中的多多了;
顶层const,底层const,constexpter,种种const层出不穷。
没关系,随着小编的脚步一一认识一下他们!

我们先讨论指针,再讲讲引用。

一. 指针
1.顶层const——值不变的const
顶层const(top-level-const)是指该 指针 本身是一个常量,即指针值为一个常量,他可以指向常量(前提有底层const,下面会讲到),也可以指向非常量。
在指针中,往往把这种指针叫做常量指针(coonst pointer).

/*#include <iostream>using namespace std;int main(){    //指针可以定义为常量    int number = 0;    int * const p1 = &number;//常值指针,恒定指向,顶层const    int num = 99;    //p1 = &num;失败,不能将常值指针指向其他值    const double PI = 3.14159267;    const double* const p2 = &PI;//第一个表示为指向常值(不会修改所指向值),第二个为常值指针    cout << *p2 << endl;    return 0;}*/

2.底层const——自以为是的const
底层const(low-level-const)是一个自以为是的const,一旦定义,便自觉的认为自己指向的是一个常量值,并且不去改变它(注意:其实它所指向的可以是非常量也可以是常量
这种指针叫做指向常量的指针(pointer to const).

#include <iostream>using namespace std;//pointer to const可以指向非常量,也可以被改变值int main(){    const int i = 10;//常量10    //int* p = &i; 错误,p是一个普通指针    const int* p = &i;//指向常量的指针(pointer to const),可以指向非常量    int f = 9;    cout << *p << endl;    p = &f;//可以改变值指针值,但是不能改变所指对象值    cout << *p << endl;    return 0;}

二. const 与引用
const引用很简单,注释写的很清楚,在这里就不再阑述。

#include <iostream>using namespace std;int main(){    const int i = 45 ;//const 必须在使用前初始化    const int& b = i;//常量引用    cout << b << endl;    cout << i << endl;    return 0;
#include <iostream>using namespace std;int main(){    int a = 10;    const int& r = a;//const引用可以引用一个非const值    int& r2 = a;    cout << r << endl;    r2 = 99;//对该值的修改可通过其他来进行    cout << r << endl;    return 0;}
0 0
原创粉丝点击