没有匹配的构造函数用于'mapped_type'std :: map初始化错误 [英] no matching constructor for initialization of 'mapped_type' std::map error

查看:865
本文介绍了没有匹配的构造函数用于'mapped_type'std :: map初始化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为'Card'的类,我试图将它的一些对象存储在std :: map
Card.hpp:

I have this a class called 'Card' and I am trying to store some of its objects in a std::map Card.hpp:

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:

Here is how I store and access it: 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];
}

现在,当我编译它,我得到以下错误:

Now, when I compile it I get following error:

/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.

为什么会收到此错误?我使用卡只作为一个值!

Why am I getting this error? I am using Card only as a value!

推荐答案

问题是,对于一个地图, m_deck [ _num] 旨在插入缺省构造的(如果元素尚未存在)。 Card 没有默认构造函数。

The problem is that for a map, m_deck[_num] is designed to insert a default constructed Card if the element isn't already there. And Card doesn't have a default constructor.

您可以使用 map ::找到以查看条目是否存在,而不创建一个。

You can use map::find to see if the entry is there, without creating one.

这篇关于没有匹配的构造函数用于'mapped_type'std :: map初始化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆