C++ const成员函数
来源:互联网 发布:mac怎么转音频格式 编辑:程序博客网 时间:2024/06/11 20:02
1. 首先要知道:
编译器会自动将对象本身的地址作为一个隐含参数(this)传递给类的非静态成员函数。
this指针存在于类的非静态成员函数中(全局函数,静态函数都不存在且不能使用this),指向被调用函数所在的对象。
当成员函数是非const时,this的类型是 ClassX * const,即指向非const的本类的const指针。
2. 将成员函数声明为const,本质上是将this声明成指向常量的指针。即成为指向const的本类类型的const指针。
在某类ClassX中有非静态成员函数ClassX::int fun(int a) const {this.a=a;}相当于ClassX::int fun(const ClassX *const this) {//C++中this是隐式的,不能显示定义thisthis.a=a}由于第二种写法是非法的,因此化为第一种写法,在成员函数后加const,修饰this。
3. 用const声明一个类的对象时,对象类型是const ClassX * const,而其非const的成员变量中this指示的本类类型是ClassX * const。在调用时会发生类型不匹配错误。
因此,非const对象可以调用const和非const的成员函数;const对象只能调用const成员函数,且此const成员函数中不能修改成员变量。如下:
class ClassX {public: int a; ClassX(int a) { this -> a = a; } int fun(int a) const {//这里无论带不带const都不会通过编译,因为修改了const对象的成员变量 this -> a = a; }};//codeblocks下编译不通过,提示 assignment of member 'ClassX::a' in read-only objectint main(){ const ClassX classX(2); classX.fun(3);//const对象调用const成员函数 return 0;}
4.另外,构造函数不能被声明为const的,当我们创建一个const对象时,直到构造函数完成初始化过程,对象才真正取得其“常量”属性。因此,构造函数可以在const对象的构造过程中向其写值。
阅读全文
0 0
- c++const成员函数
- 高质量c++(const成员函数)
- 高质量c++(const成员函数)
- 高质量c++(const成员函数)
- 高质量c++(const成员函数)
- 第二遍C++primer->const成员函数
- c++const成员函数与mutable关键词
- const对象const成员函数
- const成员函数及const
- const成员函数
- const成员函数
- const 成员函数
- c++ const 成员函数
- 关于const成员函数
- const成员函数简介
- const 成员函数
- c++ const成员函数
- c++ const成员函数
- Omnibus GitLab 使用说明
- HDU 5536 Chip Factory ACM/ICPC 2015 Changchun(Trie)
- 06jquery filternot has
- spring 配置多个数据源(基于JPA)
- 向量在游戏开发中的应用(二)
- C++ const成员函数
- GEM5 Tutorial
- 使用Node+Koa2+Mysql搭建简易博客
- java.lang.UnsupportedClassVersionError: Bad version number in .class file
- 我的第一篇博客
- select2默认选中
- 出勤记录I (水道DP)
- java的递归和copy文件艺术
- Android传输数据时Rsa加密解密详解