我是靠谱客的博主 小巧太阳,这篇文章主要介绍类中的const成员,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream> using namespace std; class Base { const int a; public: Base(int _a):a(_a){} //Base(int _a) { a = _a; } //error }; int main() { return 0; }
在类中声明变量为const类型,但是不可以初始化

const常量的初始化必须在构造函数初始化列表中初始化,而不可以在构造函数函数体内初始化




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
#include<iostream> using namespace std; class Base { const int const_a; int b; public: Base(int _const_a = 1, int _b=1) :const_a(_const_a) { b = _b; } int Get() const { //b = 1;//error:不能对类成员变量修改,但是如果你一定要修改,可以使用关键字mutable声明这个类成员变量,具体使用参考百度 int c = b;//right,因为c是局部变量,不像b是类成员 return b; } }; int main() { return 0; }

复制代码
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
38
39
40
41
42
43
44
45
46
#define _CRT_SECURE_NO_DEPRECATE //#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #include<iostream> using namespace std; class Base { const int const_a; int b; public: Base(int _const_a = 1, int _b=1) :const_a(_const_a) { b = _b; } void Func(){} void ConstFunc()const{} int ConstGet() const //const成员函数 { //不管是不是const成员变量,都可以使用 int temp = const_a;//right int temp2 = b;//right //Func();//error:const类成员函数不能调用非const成员函数 ConstFunc();//reght return b; } int NonConstGet()//非const类成员函数 { //不管是不是const成员变量,都可以使用 int temp = const_a;//right int temp2 = b;//right Func();//right ConstFunc();//right return b; } }; int main() { return 0; }

但是,如果据成员是指针,则const成员函数并不能保证不修改指针指向的对象,编译器不会把这种修改检测为错误。例如,

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
class Name { public: void setName(const string &s) const; private: char *m_sName; }; void setName(const string &s) const { m_sName = s.c_str(); // 错误!不能修改m_sName; for (int i = 0; i < s.size(); ++i) m_sName[i] = s[i]; // 不好的风格,但不是错误的 }

复制代码
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
#define _CRT_SECURE_NO_DEPRECATE //#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #include<iostream> using namespace std; class Base { public: Base(){} void Func(){} void ConstFunc()const{} }; int main() { const Base constBase; //constBase.Func();//error:const类对象不能调用非const成员函数 // 在C++中,只有被声明为const的成员函数才能被一个const类对象调用。 constBase.ConstFunc();//right Base base; base.Func();//right base.ConstFunc();//right return 0; }




最后

以上就是小巧太阳最近收集整理的关于类中的const成员的全部内容,更多相关类中内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部