运算符的C ++ const问题==

时间:2018-07-29 12:17:07

标签: c++ operator-overloading const

我正在为包含一些STL容器(operator==)的类编写一个简单的map。当我尝试将输入参数指定为const时, 编译失败。没有const,一切都很好。这是我的代码和编译错误。

$ cat Readinfo.h
#ifndef __READINFO_H__
#define __READINFO_H__

#include <map>
#include <string>

class Readinfo {
public:
    bool operator==(const Readinfo &that);
    std::map<std::string,std::string> readinfo;
};

#endif

这是源文件:

$ cat Readinfo.cpp
#include "Readinfo.h"

bool Readinfo::operator==(const Readinfo &that)
{
    for (const auto it:readinfo)
    {
        if (readinfo[it.first] != that.readinfo[it.first])
        {
            return false;
        }
    }
    return true;
}
int main(int argc, char **argv)
{
    Readinfo r;
    return 0;
}

编译行+错误:

$ g++ -o main Readinfo.cpp
Readinfo.cpp: In member function ‘bool Readinfo::operator==(const Readinfo&)’:
Readinfo.cpp:7:51: error: passing ‘const std::map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive]
   if (readinfo[it.first] != that.readinfo[it.first])
                                                   ^
In file included from /usr/include/c++/7/map:61:0,
             from Readinfo.h:4,
             from Readinfo.cpp:1:
/usr/include/c++/7/bits/stl_map.h:484:7: note:   in call to ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = std::__cxx11::basic_string<char>; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::__cxx11::basic_string<char>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::__cxx11::basic_string<char>]’
   operator[](const key_type& __k)
   ^~~~~~~~

我错了什么?谢谢!

0 个答案:

没有答案