Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

c++ - Returning non-const reference from a const member function

Why does returning the reference to a pointed-to member variable work, but not the other? I know that a const member function should only return const references, but why does that not seem true for pointers?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; }  // obviously bad

In a const-function, every data member becomes const in such way that it cannot be modified. int becomes const int, int * becomes int * const, and so on.

Since the type of a in your first function becomes int * const, as opposed to const int *, so you can change the data (which is modifiable):

  m.geta() = 5;  //works, as the data is modifiable

Difference between : const int* and int * const.

  • const int* means the pointer is non-const, but the data the pointer points to is const.
  • int * const means the pointer is const, but the data the pointer points to is non-const.

Your second function tries to return const int &, since the type of b become const int. But you've mentioned the actual return type in your code as int &, so this function would not even compile (see this), irrespective of what you do in main(), because the return type doesn't match. Here is the fix:

 const int & getb(void) const { return b; }  

Now it compiles fine!.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...