从const成员函数返回非const引用

Ben*_*ard 7 c++ pointers const reference

为什么返回对指向成员变量的引用有效,而不是另一个?我知道一个const成员函数应该只返回const引用,但为什么这对指针来说似乎不正确呢?

class MyClass
{
  private:
    int * a;
    int b;
  public:
    MyClass() { a = new int; }
    ~MyClass() { delete a; }

    int & geta(void) const { return *a; } // good?
    int & getb(void) const { return b; }  // obviously bad
};

int main(void)
{
  MyClass m;

  m.geta() = 5;  //works????
  m.getb() = 7;  //doesn't compile

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 22

int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; }  // obviously bad
Run Code Online (Sandbox Code Playgroud)

在const函数中,每个数据成员都以无法修改的方式变为const .int成为const int,int *成为int * const,等等.

由于类型a在你的第一个功能变得int * const,而不是const int *,所以你可以改变的数据(这是修改):

  m.geta() = 5;  //works, as the data is modifiable
Run Code Online (Sandbox Code Playgroud)

区别:const int*int * const.

  • const int*表示指针是非const的,但指针指向的数据是const.
  • int * const指的是指针是const,但指针指向的数据是非const.

你的第二个函数试图返回const int &,因为该类型bconst int.但是你已经在代码中提到了实际的返回类型int &,所以这个函数甚至不会编译(见这个),不管你做什么main(),因为返回类型不匹配.这是修复:

 const int & getb(void) const { return b; }  
Run Code Online (Sandbox Code Playgroud)

现在编译好了!.


GMa*_*ckG 6

因为a成了int * const a;.也就是说,你不能改变a(改变它指向的)的价值,就像const说的那样.所a 指出的一致性是一个完全不同的问题.

请参阅我的答案在这里为常量和const成员函数进行深入讨论.