Const at the end of function declaration in C++
Possible Duplicate:
Meaning of “const” last in a C++ method declaration?
In the below function declaration,
const char* c_str ( ) const;
what does the second const do ?
It means the method is a "const method" A call to such a method cannot change any of the instance's data (with the exception of mutable
data members) and can only call other const methods.
Const methods can be called on const or non-const instances, but non-const methods can only be called on non-const instances.
struct Foo {
void bar() const {}
void boo() {}
};
Foo f0;
f0.bar(); // OK
fo.boo(); // OK
const Foo f1;
f1.bar(); // OK
f1.boo(); // Error!
That const
can only tag onto member functions. It guarantees that it will not change any of the object's data members.
For example, the following would be a compile-time error because of it:
struct MyClass
{
int data;
int getAndIncrement() const;
};
int MyClass::getAndIncrement() const
{
return data++; //data cannot be modified
}
It is a modifier that affects that method (it is only applyable to methods). It means that it will only access, but not modify the state of the object (ie, no attributes will be changed).
Another subtle change is that this method can only call other const
methods (it would not make sense to let it call methods which will probably modify the object). Sometimes, this means that you need two versions of some methods: the const
and the non- const
one.
上一篇: 为什么要在最后加上一个“const”?
下一篇: Const在C ++函数声明结束时