Why the use of const in a method with no parameters?
This question already has an answer here:
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
表示该函数不会修改它所属的类中的成员数据。
上一篇: 这是什么意思const类型和方法
下一篇: 为什么在没有参数的方法中使用const?