我把這種現象稱之爲一類「卡」,我試圖來存儲一些在一個std ::對象地圖 Card.hpp:爲「mapped_type」的std ::地圖初始化不匹配構造錯誤
class Card
{
public:
enum ValueType { NOVALUE, ACE };
enum FaceType { NOFACE, CLUBS };
Card(const ValueType & _value, const FaceType & _face);
Card(const Card & _card);
private:
ValueType m_value;
FaceType m_face;
};
這是我如何存儲和訪問它: Deck.hpp:
#include <map>
class Card;
class Deck
{
public:
Deck();
std::size_t length() const;
Card get_card(const int & _num);
private:
std::map<int, Card> m_deck;
};
Deck.cpp:
#include "Card.hpp"
Deck::Deck()
{
m_deck.insert(std::pair<int, Card>(0, Card(Card::NOVALUE, Card::NOFACE)));
m_deck.insert(std::pair<int, Card>(1, Card(Card::ACE, Card::CLUBS)));
}
std::size_t Deck::length() const
{
return m_deck.size();
}
Card Deck::get_card(const int & _num)
{
return m_deck[_num];
}
現在,當我編譯它,我得到以下錯誤:
/usr/include/c++/4.6/bits/stl_map.h:453:45: error: no matching constructor for initialization of 'mapped_type' (aka 'Card')
__i = insert(__i, value_type(__k, mapped_type()));
^
Deck.cpp:69:18: note: in instantiation of member function 'std::map<int, Card, std::less<int>, std::allocator<std::pair<const int, Card> > >::operator[]' requested here
return m_deck[_num];
^
./Card.hpp:30:2: note: candidate constructor not viable: requires 2 arguments, but 0 were provided
Card(const ValueType & _value, const FaceType & _face);
^
./Card.hpp:32:2: note: candidate constructor not viable: requires 1 argument, but 0 were provided
Card(const Card & _card);
^
1 error generated.
爲什麼會出現這個錯誤?我僅將卡用作價值!
這工作'返回m_deck.find(_num) - >第二;' –
它只適用於'_num'元素存在。否則find會返回'm_deck.end()',它沒有'second'。 –
是的,但這比嘗試返回默認對象更接近預期的結果。至少對於我來說。 –