const pointer(const指针)

来源:互联网 发布:常用的网络端口号 编辑:程序博客网 时间:2024/05/16 10:20

c++ primer 5rd里有这样的一段话:
unlike references, pointers are objects. Hence, as with any other object type, we can have a pointer that is itself const. Like any other const object, a const pointer must be initialized, and once initialized, its value(i.e., the address that it holds) may not be changed.
也就是说,因为指针也是存在于内存中的对象,所以指针本身也可以是一个const对象。就像其他const对象一样,一个const指针也必须被第一时间初始化。并且它的值(指针存储的地址值)是不能够改变的。但是这并不表示我们就一定不可以改变const指针所指的对象的值。
看代码:

#include <iostream>int main(){        int errNumb = 0;        std::cout << "errNumb = " << std::endl;        int *const curErr = &errNumb;        const double pi = 3.14;        const double *const pip = &pi;        *curErr = 10;        std::cout << "errNumb = " << std::endl;        int tmp = 23;        curErr = &tmp;        std::cout << "*curErr = " << *curErr <<std::endl;        return 0;}

编译不通过:

xiahuixia@xiahuixia-Inspiron-3437:~/c++/primercode$ g++ -o 2.4.2 2.4.2.cpp 2.4.2.cpp: In function ‘int main()’:2.4.2.cpp:12:9: error: assignment of read-only variable ‘curErr’  curErr = &tmp;         ^

即这里出错了

curErr = &tmp;

将这行修改为:

errNumb = 23;
#include <iostream>int main(){        int errNumb = 0;        std::cout << "errNumb = " << errNumb << std::endl;        int *const curErr = &errNumb;        const double pi = 3.14;        const double *const pip = &pi;        *curErr = 10;        std::cout << "errNumb = " << errNumb << std::endl;        int tmp = 23;//      curErr = &tmp;        errNumb = 23;        std::cout << "*curErr = " << *curErr << std::endl;        return 0;}

运行结果是:

xiahuixia@xiahuixia-Inspiron-3437:~/c++/primercode$ g++ -o 2.4.2 2.4.2.cpp xiahuixia@xiahuixia-Inspiron-3437:~/c++/primercode$ ./2.4.2errNumb = 0errNumb = 10*curErr = 23
0 0
原创粉丝点击