请帮我理解以下签名:
第一个
其次,第二个
err_type funcName(const Type& buffer) const;
第一个
const
是指Type
的内容不能改变,还是指引用不能改变?其次,第二个
const
是什么意思?class foo
{
public:
void const_method() const;
void nonconst_method();
};
void doit()
{
const foo f;
f.const_method(); // this is okay
f.nonconst_method(); // the compiler will not allow this
}
此外,const方法不允许更改对象的任何成员(除非该成员被明确标记为可变):
class foo
{
public:
void const_method() const;
private:
int r;
mutable int m;
};
void foo::const_method() const
{
m = 0; // this is okay as m is marked mutable
r = 0; // the compiler will not allow this
}
是的,第一个const
表示buffer
不能更改。
第二个const
意味着这是类的成员函数,并且不会更改对象(this
)。
这个链接可以更好地解释我们大多数人可能无法描述的内容,因此我不会重复:
http://www.parashift.com/c++-faq-lite/const-correctness.html第一个const
保证函数不会改变buffer
,因此可以传递一个const缓冲区。
第二个const
仅在作为类的方法使用时才有意义。它保证调用该方法不会对包含该方法的类产生任何副作用。本质上是保证这个方法可以安全地调用const
对象。
虽然您已经得到了一些好的答案,但我认为值得指出的是,一个类可以包含mutable
成员变量。一个mutable
成员是一个您始终被允许修改的成员,即使它是const对象的一部分。这些通常用于像记忆化和缓存这样的事情,其中变量可以被修改而不影响整个对象的用户可见状态。