-2

我需要写一个新方法。给出以下代码:

const Class * func() const;

但是当类和函数都声明为常量时,这意味着什么?

4

4 回答 4

3
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.

于 2013-05-05T22:11:59.507 回答
2
const Class * func() const;
^^^^^                ^^^^^
  1                    2
  • 第一个const表示返回类型是const Class*

  • 第二个意味着,该方法func不会改变它的类成员。

 

每段§9.4/1

struct X {
   void g() const;
};

如果声明了成员函数const,则类型thisconst X*

因此,您不能修改X.

于 2013-05-05T22:11:54.863 回答
2
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.
}
于 2013-05-05T22:12:10.477 回答
0

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

于 2013-05-05T22:28:37.027 回答