意义
我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,也就是说,这些函数是"只读"函数,而有一些函数要修改类数据成员的值。如果把不改变数据成员的函数都加上const关键字进行标识,显然,可提高程序的可读性。其实,它还能提高程序的可靠性,已定义成const的成员函数,一旦企图修改数据成员的值,则编译器按错误处理。
passing 'const std:: map[*** ’ discards qualifiers [-fpermissive]
const成员函数使用map成员时出现上述错误是因为:
The issue is that you’ve marked the function as const. The operator[] on std::map is marked as non-const, and cannot be used in a const function like this. You need to manually use std::map::find (or other mechanism) to search for the input type and handle the case where it’s not found.
If you’re using C++11, you can instead use std::map::at, which IS allowed to be used on a constant map, and throws an exception if the requested element is not present.
参考:
https://stackoverflow.com/questions/20277671/c-error-passing-const-stdmapint-stdbasic-stringchar-as-this-ar
https://blog.youkuaiyun.com/qq_32739503/article/details/83341222?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
本文探讨了在C++中,当在const成员函数中尝试使用std::map的非const方法如operator[]时,会遇到的编译错误,并提供了如何正确处理这种情况的解决方案,包括使用std::map::find或std::map::at方法。
1436

被折叠的 条评论
为什么被折叠?



