开发者

C++ Classes and Overloaded Operators

I have been trying to make a StringTable class that holds a simple unordered_map<string, string>, and has the array index operator '[]' overloaded to work for accessing the map; however, the compiler will tell me that I have yet to define the overloaded operator when I try to use it. My code is as follows:

CStringTable.h

#include <string>
#include <fstream>
#include <tr1/unordered_map>

class CStringTable {
public:
    bool Load(const char* filename);

    inline const char* opera开发者_C百科tor [](const char* key);

    const char* Get(const char* key);

private:
    std::tr1::unordered_map<std::string, std::string>* m_StringMap;
};

CStringTable.cpp

#include "CStringTable.h"

inline const char* CStringTable::operator [](const char* key) {
    std::string sKey = key;

    return (*m_StringMap)[sKey].c_str();
}

I try to access the map as follows:

(*m_cStringTable)[msgKey]

where m_cStringTable is a pointer to an instance of the CStringTable class and msgKey is a const char*.

Can anybody enlighten me as to why this won't work?


Regarding the inline keyword, the compiler needs to be able to see the body of that method as well in the .h file. So either move the implementation of the operator from the .cpp file to the .h file, or include the body of the operator in the class declaration.


It seems that the type unordered_map has not the operator [] defined. Are you sure you can access the element of the map with that operator?


Here it is, per spec of unordered_map:

If inserting an element causes unordered_map::load_factor() to exceed the maximum load factor, the container increases the number of buckets and rebuilds the hash table as needed.

I'm not sure about engine of reallocation, but seems string would be copied by value. This mean that when you return const char * - in fact it can be erased by container reallocation. So pointer is unsafe and non-const.

On other hand (for example usual std::map) grants that tree is stable relative insert/remove operators and memory pointers of std::string are stable

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜