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

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

    The const qualifier means that the methods can be called on any value of foobar. The difference comes when you consider calling a non-const method on a const object. Consider if your foobar type had the following extra method declaration:

    class foobar {
      ...
      const char* bar();
    }
    

    The method bar() is non-const and can only be accessed from non-const values.

    void func1(const foobar& fb1, foobar& fb2) {
      const char* v1 = fb1.bar();  // won't compile
      const char* v2 = fb2.bar();  // works
    }
    

    The idea behind const though is to mark methods which will not alter the internal state of the class. This is a powerful concept but is not actually enforceable in C++. It's more of a promise than a guarantee. And one that is often broken and easily broken.

    foobar& fbNonConst = const_cast(fb1);
    

提交回复
热议问题