const成员函数、const类对象、mutable数据成员
来源:互联网 发布:杭州网络安防招聘 编辑:程序博客网 时间:2024/06/04 18:15
2. 类体外定义的const成员函数,在定义和声明处都需要const修饰符
1 class classname
2 {
3 public:
4 classname() {}
5 ~classname();
6
7 void foo() const;
8 char &operator[](int i);
9 private:
10 //.
11 }
12
13 void classname::foo() const
14 {
15 //
16 }
17
18 char &classname::operator[](int i)
19 {
20 //..
21 }
22 int main()
23 {
24 const classname obj();
25 obj.foo();//ok
26 obj[2];//error,coz [] not const
27 }
28
3. const对象为常量对象,它只能调用声明为const的成员函数。但是构造函数和析构函数是唯一不是const成员函数却可以被const对象调用的成员函数。 当然,一般对象当然也可以调用const成员了
1 class A
2 {
3 public:
4 A(int x, int y) : _x(x), _y(y) {}
5 //int get() { return _x;}
6 int get() const { return _y;}
7 private:
8 int _x, _y;
9 };
10
11 int main()
12 {
13 A obj(2, 3);
14 const A obj1(2, 3);
15 cout << obj.get() << " " << obj1.get();//3 3
16
17 return 0;
18 }
19
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 A(int x, int y) : _x(x), _y(y) {}
8 int get() { return _x;}
9 //int get() const { return _y;}
10 private:
11 int _x, _y;
12 };
13
14 int main()
15 {
16 A obj(2, 3);
17 const A obj1(2, 3);
18 cout << obj.get() << " " << obj1.get();
19 //错误,obj1为常量对象,不能调用非const方法
20 return 0;
21 }
4. const成员函数可以被相同参数表的非const成员函数重载
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 A(int x, int y) : _x(x), _y(y) {}
8 int get() { return _x;}
9 int get() const { return _y;}
10 private:
11 int _x, _y;
12 };
13
14 int main()
15 {
16 A obj(2, 3);
17 const A obj1(2, 3);
18 cout << obj.get() << " " << obj1.get();
19 // 2 3
20 return 0;
21 }
22
4. 为了允许修改一个类的成员变量,即使是一个const对象的数据成员,于是引入了mutable
通过将数据成员声明为mutable, 表明此成员总是可以被更新,即使在一个const成员函数中。
- const成员函数、const类对象、mutable数据成员
- C++回顾之const对象、const成员函数、mutable类型
- C++回顾之const对象、const成员函数、mutable类型
- const成员函数和mutable
- const成员函数和mutable
- const 和 volatile 成员函数、mutable 数据成员
- const static与类的数据成员,成员函数,对象
- const对象const成员函数
- C++的const类成员函数(解释为什么非const成员函数不能访问const对象的数据成员)
- const成员函数和mutable关键字
- const只读成员函数与mutable
- c++const成员函数与mutable关键词
- 十四、对象的使用(二)const成员函数、const对象、mutable
- C++学习笔记之——回顾const对象、const成员函数、mutable类型
- 类const成员函数
- const对象调用非const成员函数
- const成员函数与const对象
- const对象和const成员函数
- iOS 开发环境的搭建
- STM32 GPIO_2 8种工作方式
- C++ 函数后加const
- 切换eclipse package explorer字体大小
- iOS-C语言-C语言的介绍以及第一个例子HelloWorld
- const成员函数、const类对象、mutable数据成员
- android.content.res.Resources$NotFoundException: String resource ID #0x7b
- Android开发中webView与HTML+JS的交互
- PC管理端及评委手机打分端的浏览器兼容问题
- HDU 1753 大明A+B
- iOS-沙盒机制-整合篇
- mysql如何处理auto_increment
- 芯片启动过程 ARM C51 Soc - RTOS LINUX - 之一
- CardView的学习