Why the use of const in a method with no parameters?

This question already has an answer here:

  • Meaning of “const” last in a C++ method declaration? 7 answers
  • What is meant with “const” at end of function declaration? [duplicate] 6 answers

  • Banning the modification of members is not the only reason to qualify a member function as const . Whether you want to modify members or not, you can only call a member function on an object through a const context if the member function is marked const :

    #include <iostream>
    #include <string>
    
    struct List
    {
       std::string reqClubName()
       {
          return m_Club;
       }
    
    private:
       std::string m_Club;
    };
    
    int main()
    {
       const List l;
       std::cout << l.reqClubName();
       // ^ illegal: `l` is `const` but, `List::reqClubName` is not
    }
    

    Neither the language nor the compiler care that reqClubName doesn't try to modify the object anyway; your program will not compile.

    Because of this, a const suffix should be your default approach unless you do need to modify a data member.


    成员函数后的const表示该函数不会修改它所属的类中的成员数据。

    链接地址: http://www.djcxy.com/p/40436.html

    上一篇: 这是什么意思const类型和方法

    下一篇: 为什么在没有参数的方法中使用const?