Meaning of 'const' last in a function declaration of a class?

后端 未结 10 2309
无人共我
无人共我 2020-11-21 06:37

What is the meaning of const in declarations like these? The const confuses me.

class foobar
{
  public:
     operator int () const         


        
10条回答
  •  抹茶落季
    2020-11-21 07:20

    Meaning of a Const Member Function in C++ Common Knowledge: Essential Intermediate Programming gives a clear explanation:

    The type of the this pointer in a non-const member function of a class X is X * const. That is, it’s a constant pointer to a non-constant X (see Const Pointers and Pointers to Const [7, 21]). Because the object to which this refers is not const, it can be modified. The type of this in a const member function of a class X is const X * const. That is, it’s a constant pointer to a constant X. Because the object to which this refers is const, it cannot be modified. That’s the difference between const and non-const member functions.

    So in your code:

    class foobar
    {
      public:
         operator int () const;
         const char* foo() const;
    };
    

    You can think it as this:

    class foobar
    {
      public:
         operator int (const foobar * const this) const;
         const char* foo(const foobar * const this) const;
    };
    

提交回复
热议问题