我需要写一个新方法。给出以下代码:
const Class * func() const;
但是当类和函数都声明为常量时,这意味着什么?
const Class * func() const;
是const Class*
返回类型。它说这个函数返回一个指向 a 的指针const Class
。所以调用这个函数的人都会收到一个指针,但是他们不能修改它指向的对象。
The const
at the end of the declaration says that this member function does not modify the state of the object it is being called on. That is, it doesn't modify the object that this
points at. In fact, if you try to modify any data member (that is not mutable
) in func
, the compiler will tell you off.
const Class * func() const;
^^^^^ ^^^^^
1 2
第一个const
表示返回类型是const Class*
。
第二个意味着,该方法func
不会改变它的类成员。
每段§9.4/1
:
struct X {
void g() const;
};
如果声明了成员函数
const
,则类型this
为const X*
因此,您不能修改X
.
const Class * ...
This means func
will return a const pointer
to Class
Class c;
Class* p = c.func() // Not allowed.
const Class* p = c.func() // OK.
p->mem = 2; // Not allowed. p is a const pointer.
func() const;
^^^^
means func
will not modify this
or in other words does not affect the state of the class (doesn't modify any member variables.).
void Class::func(int& i) const {
this->mem = i; // is not allowed here since func() is const (unless 'mem' is mutable)
i = this->mem; // This is OK.
}
It means nothing changes! const means the thing is invariant
i.e
const Class
- Cannot have fun with thwereply
func() const;
That object cannot play with itself