在课上,通过引用传递参数,我们覆盖的传递函数参数为const变量的优点。总的来说,决策变量常量确保它们的值是不小心更改。这是特别重要的传递变量的参考,为来电者一般不会期望值传递给一个函数被改变。
就像内置的数据类型(int,char,双,等),类的对象可以通过使用const关键字声明为const。所有的const变量必须在创建时初始化。在内置数据类型的情况下,在实例是通过显式或隐式的作业完成:
1
2
const int nValue = 5; // initialize explicitly
const int nValue2(7); // initialize implictly
在类的情况下,这是通过构造函数初始化:
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试图改变一个成员变量或调用成员函数,试图改变一个成员变量的常量。
现在,考虑下面的电话:
1
std::cout << cSomething.GetValue();