When I tried to compile the following codes in VS2010, error C2678 prompted.
#include <string>
#include <map>
using namespace std;
class test
{
private:
map<string, string> data;
public:
test(){};
~test(){};
public:
const string & get(const string & key)const{return data[key];}; //error C2678
bool set(const string & key, const string & value){data[key]=value;return true;};
};
void main()
{
const string key="Hello world!";
const string value="I'm coming!";
test t;
t.set(key,value);
t.get(key);
}
But when I leave it as functions like
#include <string>
#include <map>
using namespace std;
bool set(const string & key, const string & value, map<string, string> & data)
{
data[key]=value;
return true;
}
const string & get(const string & key, map<string, string> & data)
{
return data[key];
}
void main()
{
const string key="Hello world!";
const string value="I'm coming!";
map<string, string> data;
set(key, value, data);
get(key;
}
It does compile and runs.
Does anyone know what’s the problem about?
You’ve declared the get member function of your test class as const. But the
std::mapoperator[]is a non const function, so it cannot be called from a const function. Use thefindfunction instead.The reason
operator[]is non const is because if the key does not exist, then it inserts it into the map along with a default constructed value.