继续const用法
来源:互联网 发布:湖南教师网络研修平台 编辑:程序博客网 时间:2024/06/08 19:20
const可以用在类型前面,也可以用在变量前面,比如看下面一段代码:
#include <iostream>using namespace std;int main(){int a=5,b=6;const int *p1=&a;int * const p2=&a;const int* const p3=&a;/* 自身值和指向的值都不可改变 */a=6; /* a是一个变量,可以重新赋值 */*p1=2; /* p1指向的值不可改变, 编译出错 */p1=&b; /* p1指向的值不可改变,p1本身的值可以改变(附带效果p1指向的值改变了) */p2=&b; /* p2的值不可改变,编译出错 */*p2=3; /* p2指向的值非const,可以修改没有问题 */return 0;}注释很清楚了,再举一个关于p3的例子:类的常成员函数。代码如下:
void func2(int a, int b) const;
假设func2是某个类的常成员函数,大家都知道这个const修饰的是this指针,那么const是如何修饰这个this指针的?是p1的方式、p2的方式‘还是p3的方式。我们使用具体代码证明一下:
.h文件
#pragma onceclass test{public:int m_a;int m_b;public:void func1(int a, int b);void func2(int a, int b) const;};.cpp文件,只看func2函数实现
void test::func2(int a, int b) const{cout<<"this="<<this<<endl;cout<<"(*this).m_a="<<(*this).m_a<<endl;cout<<"(*this).m_b="<<(*this).m_b<<endl;this++;(*this).m_b=b;cout<<"this="<<this<<endl;cout<<"(*this).m_a="<<(*this).m_a<<endl;cout<<"(*this).m_b="<<(*this).m_b<<endl;}main.cpp文件
int main(){test *a=new test;a->func1(1,1);a->func2(2,3);delete a;return 0;}编译时出错,看出错原因
很明显this常量,this所指向的值也是常量。const不仅修饰了this还修饰了类的类型。常成员成员函数展开来写应该是:
void func2(int a, int b, const test* const this);
阅读全文
1 0
- 继续const用法
- const用法
- const用法
- const用法
- const用法
- const用法
- const 用法
- const用法
- const 用法
- const用法
- const用法
- const用法
- const用法
- const用法
- const用法
- CONST用法
- const用法
- const用法
- JAVA开发之 28- JAVA的循环结构
- Opencv 人脸检测训练分类器,及其常见问题
- iOS开发 给View添加指定位置的边框线
- 《深入理解计算机系统(原书第2版)》pdf
- 如何将自己在github写的android library开源,让大家依赖使用
- 继续const用法
- Latex 参考文献上标
- Trafodion Troubleshooting
- Java:实现简单的连接池
- struts2.xml配置详解
- spring+myBatisi实现多数据源动态切换
- layer-------弹出层参数介绍
- 再谈java的内存泄露
- Hive SQL执行计划深度解析