簡體   English   中英

std ::對std :: string和自定義類無法復制到std :: map :: insert(std :: make_pair(string,class))

[英]std::pair of std::string and custom class fails to copy on std::map::insert(std::make_pair(string, class))

這個錯誤:

error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion)  c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility  216

發生在這個函數的唯一一行:

void Animation::AddAnimation(std::string name, AnimationFrameSet& animation) {
    _animations.insert(std::make_pair(name, animation));
}

_animations是一個std::map<std::string, AnimationFrameSet>

AnimationFrameSet聲明了一個operator =(...)和一個復制構造函數,但奇怪的是,編譯器說它在嘗試復制const std::string時失敗了......即使const std::string甚至沒有被傳入const

我不能為我的生活弄清楚(甚至記住!:P)為什么這是/應該拋出/拋出錯誤。

謝謝。

編輯

我有點困惑為什么這不起作用的原因是一個不同的類使用非常相似的實現,它不會拋出錯誤:

BITMAP* BitmapCache::GetBitmap(std::string filename) {
    //Return NULL if a bad filename was passed.
    if(filename.empty()) return NULL;
    if(exists(filename.c_str()) == false) return NULL;

    //Reduce incorrect results by forcing slash equality.
    filename = fix_filename_slashes(&filename[0]);

    //Clean the cache if it's dirty.
    CleanCache();

    //Search for requested BITMAP.
    MapStrBmpIter _iter = _cache.find(filename);

    //If found, return it.
    if(_iter != _cache.end()) return _iter->second;

    //Otherwise, create it, store it, then return it.
    BITMAP* result = load_bmp(filename.c_str(), NULL);
    if(result == NULL) return NULL;
    /*Similar insert line, a non-const std::string that was passed in is passed to a std::make_pair(...) function*/
    _cache.insert(std::make_pair(filename, result));
    return result;
}

類型定義:

typedef std::map<std::string, BITMAP*> MapStrBmp;
typedef MapStrBmp::iterator MapStrBmpIter;

由於_animations是一個std::map ,嘗試使用另一種插入方法,例如:

_animations[name] = animation;

但更重要的是檢查AnimationFrameSet類是否具有有效的復制構造函數和賦值運算符。 如果不是,您可能希望使用智能指針類,例如:

typedef std::shared_ptr<AnimationFrameSet> AnimationFrameSetPtr;

然后地圖將是:

std::map<std::string, AnimationFrameSetPtr>

這是失敗的原因是因為您使用的std :: map容器需要一個const值作為鍵值。

這里查看std :: map的文檔。

例:

class TestClass
{
};

std::map< const std::string, TestClass > myMap;
std::pair< const std::string, TestClass > firstElement = std::make_pair("test", TestClass() );
myMap.insert( firstElement );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM