可能重复:
What's the use of const here
Using 'const' in class's functions
大家好,
我一直在使用const方法和变量来犯错误。例如,有时我使用
const int myfunc(const int &obj) const { }
其他一些时候我觉得我最后不需要const,因为参数已经是const,所以我不明白为什么我应该通过在最后附加一个const来强制执行这个事实。
答案 0 :(得分:5)
const int myfunc(const int &obj) const { }
const
表示返回值是常量。在这种特殊情况下,它并不是特别相关,因为int
是一个值而不是参考。const
表示参数obj
是常量。这向调用者表明该函数不会修改该参数。const
表示函数myfunc
是常量。这向调用者指示该函数不会修改该函数所属类的非可变成员变量。关于#3,请考虑以下事项:
class MyClass
{
void Func1() { ... } // non-const member function
void Func2() const { ... } // const member function
};
MyClass c1; // non-const object
const MyClass c2; // const object
c1.Func1(); // fine...non-const function on non-const object
c1.Func2(); // fine... const function on non-const object
c2.Func1(); // oops...non-const function on const object (compiler error)
c2.Func2(); // fine... const function on const object
答案 1 :(得分:4)
Noel Llopis为游戏开发者在C ++中写了一篇关于const的伟大章节。
查看他的博客文章http://gamesfromwithin.com/the-const-nazi,以获得对const的详细解释。
答案 2 :(得分:0)
最后的const表示成员变量相对于类的常量。它表明它不会改变任何类的状态。开头的const表示int类型的常量。