C++ Const 成员函数(初级)

C++ Const Member Function (Beginner)

在 C++ Primer P259 中,它说

Objects that are const, and references or pointers to const objects, may call only const member functions.

然而,根据我目前的理解,指向 const 对象的指针不一定适用,因为指针本身是非常量的。只要成员函数不修改指向的对象,在指向常量对象的指针上调用非常量成员函数是合法的。
正确吗?

编辑:好的我现在明白了,这是因为当我们"call member function on the pointer"时,我们实际上是先取消引用它,然后使用下面的对象。

引用正确。

试试这个

class TestClass
{
public:
  void nonconst(){};

  void constMethod() const {}
};

int main()
{

  TestClass const *s = new TestClass();
  //s->nonconst(); // (1) no not legal
  s->constMethod();

  s = new TestClass(); // (2) yes legal
  s->constMethod();
}
  1. s 是一个指向常量的指针。调用非 const 方法会导致

passing ‘const TestClass’ as ‘this’ argument discards qualifiers [-fpermissive]

  1. 但是 s 可以指向不同的实例。如评论中所述,指针可以指向不同的变量。