在课上,通过引用传递参数,我们覆盖的传递函数参数为const变量的优点。总的来说,决策变量常量确保它们的值是不小心更改。这是特别重要的传递变量的参考,为来电者一般不会期望值传递给一个函数被改变。
就像内置的数据类型(int,char,双,等),类的对象可以通过使用const关键字声明为const。所有的const变量必须在创建时初始化。在内置数据类型的情况下,在实例是通过显式或隐式的作业完成:
1
2
|
const
int
nValue = 5;
// initialize explicitly
const
int
nValue2(7);
// initialize implictly
|
1
2
|
const
Date cDate;
// initialize using default constructor
const
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;
}
|
令人惊讶的是,这将导致一个编译错误!这是因为const对象只能调用const成员函数,getvalue()未被标记为const成员函数。const成员函数是一个成员函数,保证它不会改变任何类变量或任何非const成员函数调用。
让getvalue() const成员函数中,我们只需将const关键字函数原型: