可能的重复:
const 这里有什么用 https://stackoverflow.com/questions/2025159/whats-the-use-of-const-here
在类的函数中使用“const” https://stackoverflow.com/questions/2157458/using-const-in-classs-functions
Hi All,
我在类方法和变量中使用 const 时不断犯错误。例如,有时我使用以下方法解决问题
const int myfunc(const int &obj) const { }
有时我觉得最后不需要 const,因为参数已经是 const,所以我不明白为什么应该通过在末尾附加 const 来强制执行这一事实。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)