所有三个涉及csomething以上线是非法的因为他们违反csomething试图改变一个成员变量或调用成员函数,试图改变一个成员变量的常量。
现在,考虑下面的电话:
1
2
3
4
5
6
7
8
9
10
11
12
|
class
Something { public : int
m_nValue; Something()
{ m_nValue = 0; } void
ResetValue() { m_nValue = 0; } void
SetValue( int
nValue) { m_nValue = nValue; } int
GetValue() const
{ return
m_nValue; } }; |
现在getvalue()了const成员函数,这意味着我们可以称它为任何const对象。
const成员函数的类定义之外声明必须指定在函数原型中类的定义和代码文件中的函数原型const关键字:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class
Something { public : int
m_nValue; Something()
{ m_nValue = 0; } void
ResetValue() { m_nValue = 0; } void
SetValue( int
nValue) { m_nValue = nValue; } int
GetValue() const ; }; int
Something::GetValue() const { return
m_nValue; } |
1
2
3
4
5
6
7
|
class
Something { public : int
m_nValue; void
ResetValue() const
{ m_nValue = 0; } }; |