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

后端 未结 10 2090
无人共我
无人共我 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:19

    Blair's answer is on the mark.

    However note that there is a mutable qualifier which may be added to a class's data members. Any member so marked can be modified in a const method without violating the const contract.

    You might want to use this (for example) if you want an object to remember how many times a particular method is called, whilst not affecting the "logical" constness of that method.

    0 讨论(0)
  • 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;
    };
    
    0 讨论(0)
  • 2020-11-21 07:22

    when you use const in the method signature (like your said: const char* foo() const;) you are telling the compiler that memory pointed to by this can't be changed by this method (which is foo here).

    0 讨论(0)
  • 2020-11-21 07:27

    The const keyword used with the function declaration specifies that it is a const member function and it will not be able to change the data members of the object.

    0 讨论(0)
提交回复
热议问题