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 = π *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 = π *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
- const pointer(const指针)
- Const & Pointer
- const & Pointer
- const pointer
- const && pointer
- const pointer
- Pointer to Const & const pointer
- const pointer 和pointer const
- pointer on C_2 基本数据类型 指针 const
- 常量指针(const pointer)和指向常量的指针(pointer to const)
- const Pointers and Pointer to const Objects 常量指针和指向常量对象的指针
- pointer and const
- 关于const于pointer
- const pointer的读法
- const pointer and array
- const,template,pointer,virtual
- Pointer and Const
- const And pointer
- 汇编语言初步理解
- 友元类
- Android布局
- 语音识别中基于规则的语言模型
- Android使用Intent实现页面跳转
- const pointer(const指针)
- USACO-Section 4.2 The Perfect Stall (二分图最大匹配[匈牙利算法[DFS]||网络流[Ford-Fulkerson]])
- “Linux内核分析”实验报告8
- TCP/IP(二):数据链路层和网络层
- POJ 1426 find the mltiple(dfs)
- 关于邮箱前端架构的一些思考
- 20160417记录 line-height
- HDFS shell 中-du -df 用法详解
- Python数据类型和相关函数方法