我是靠谱客的博主 传统画笔,这篇文章主要介绍C++语言—类的const成员,现在分享给大家,希望可以做个参考。

const修饰普通变量:
在C++中,const修饰的变量已经为一个常量,具有宏的属性,即在编译期间,编译器会将const所修饰的变量进行替换。
const修饰类成员:

 const修饰类成员变量时,该成员变量必须在构造函数的初始化列表中初始化

 const修饰类成员函数,实际修饰该成员函数隐含的this指针指向的内容,该成员函数中不能对类的任何成员进行修改

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Date { public: Date(int year,int month,int day) :_year(year) //_year只能在此处初始化 ,_month(month) ,_day(day) {} void show() const { // this->_day = 2018; //函数体内无法改变类成员变量 cout << _year<<"-"<< _month<<"-"<< _day << endl; } private: const int _year; int _month; int _day; };

 在const修饰的成员函数可能需要对类的某个成员变量进行修改,该成员变量只需被mutable关键字修饰即可

来看看以下几种场景:

1. 和const对象可以调用非const成员函数const成员函数吗?

2. 非const对象可以调用非const成员函数和const成员函数吗?

3. const成员函数内可以调用其它的const成员函数和非const成员函数吗?

4. 非const成员函数内可以调用其它的const成员函数和非const成员函数吗?

通过以下代码及其中的注释理解这里的问题是很容易的:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Date { public: Date(int year,int month,int day) :_year(year) ,_month(month) ,_day(day) {} void Displayinfo() //非const函数 { showinfo(); //非const成员函数可以调用const成员函数 cout << _year << "-" << _month << "-" << _day << endl; } void showinfo() const //const函数 { // Displayinfo(); //const成员函数不可以调用非const成员函数 cout << _year<<"-"<< _month<<"-"<< _day << endl; } private: const int _year; int _month; int _day; }; void test1() { const Date d1(2000,1,1); //const对象 Date d2(2018, 9, 6); //非const对象 // d1.Displayinfo(); //const对象不可以调用非const成员函数 d1.showinfo(); //const对象可以调用const成员函数 d2.Displayinfo(); //非const对象可以调用非const成员函数 d2.showinfo(); //非const对象可以调用const成员函数 }

 关于类的const成员这块就说这么多

最后

以上就是传统画笔最近收集整理的关于C++语言—类的const成员的全部内容,更多相关C++语言—类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(156)

评论列表共有 0 条评论

立即
投稿
返回
顶部