在课上,通过引用传递参数,我们覆盖的传递函数参数为const变量的优点。总的来说,决策变量常量确保它们的值是不小心更改。这是特别重要的传递变量的参考,为来电者一般不会期望值传递给一个函数被改变。
就像内置的数据类型(int,char,双,等),类的对象可以通过使用const关键字声明为const。所有的const变量必须在创建时初始化。在内置数据类型的情况下,在实例是通过显式或隐式的作业完成:
|
1
2
|
const
int
nValue = 5; //
initialize explicitlyconst
int
nValue2(7); //
initialize implictly |
|
1
2
|
const
Date cDate; //
initialize using default constructorconst
Date cDate2(10, 16, 2020); //
initialize using parameterized constructor |
如果一个类没有使用参数化构造函数初始化,必须提供一个公共的默认构造函数,如果没有公共的默认构造函数是在这种情况下,编译器就会出现错误。
一旦一个const对象已被初始化通过构造函数,任何试图修改的对象的成员变量是不允许的,因为它违反了对象的常量。这包括改变成员变量直接(如果他们是公开的),或调用成员函数集的成员变量的值:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class
Something{public: int
m_nValue; Something()
{ m_nValue = 0; } void
ResetValue() { m_nValue = 0; } void
SetValue(int
nValue) { m_nValue = nValue; } int
GetValue() { return
m_nValue; }};int
main(){ const
Something cSomething; //
calls default constructor cSomething.m_nValue
= 5; //
violates const cSomething.ResetValue();
//
violates const cSomething.SetValue(5);
//
violates const return
0;} |
所有三个涉及csomething以上线是非法的因为他们违反csomething试图改变一个成员变量或调用成员函数,试图改变一个成员变量的常量。
现在,考虑下面的电话:
理解C++中const关键字的使用与限制
本文深入探讨了C++中const关键字的作用,包括如何声明const变量,通过构造函数进行初始化,以及const变量在类中的使用限制。重点阐述了const变量的常量属性及其对函数参数传递的影响。
1万+

被折叠的 条评论
为什么被折叠?



