现在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;
}任何const成员函数,试图改变一个成员变量或非const成员函数的调用将导致编译器错误发生。例如:
1
2
3
4
5
6
7
class Something
{
public:
int m_nValue;
void ResetValue() const { m_nValue = 0; }
};
本文介绍了C++中常量成员函数的基本概念及其使用方法。详细解释了如何定义和使用常量成员函数,并通过示例说明了尝试在常量成员函数内修改成员变量将导致编译错误的情况。
1237

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



