为什么在STL映射中用作值的类需要在...中使用默认构造函数? [英] Why does a class used as a value in a STL map need a default constructor in ...?

查看:209
本文介绍了为什么在STL映射中用作值的类需要在...中使用默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是用作地图中值的类:

Below is the class used as the value in a map:

class Book
{
    int m_nId;
public:
    // Book() { }  <----- Why is this required?
    Book( int id ): m_nId( id ) { }

};

在main()中:

map< int, Book > mapBooks;

for( int i = 0; i &lt 10; ++i )
{
    Book b( i );
    mapBooks[ i ] = b;
}

导致错误的语句是:

mapBooks[ i ] = b;

如果我添加一个默认构造函数,错误不会出现。但是,我不明白为什么需要。任何人都可以解释?如果我使用 insert(),则不会出现问题。

If I add a default constructor, the error does not appear. However, I don't understand why the need. Can anyone explain? If I use insert(), the problem does not appear.

顺便说一句, C ++ 2008编译。

By the way, I'm using Visual C++ 2008 to compile.

推荐答案

operator [] 执行两步处理。首先,它会为给定的键找到或创建映射条目,然后返回对条目的值部分的引用,以便调用代码可以读取或写入。

operator[] performs a two step process. First it finds or creates a map entry for the given key, then it returns a reference to the value part of the entry so that the calling code can read or write to it.

在条目之前不存在的情况下,条目的值的一半需要在分配之前默认构造。

In the case where entry didn't exist before, the value half of the entry needs to be default constructed before it is assigned to. This is just the way the interface needs to work to be consistent with the case where the entry already existed.

如果需要在地图中使用这样的类型,那么你需要在地图中使用这样的类型。通过使用 find 插入 operator [] c>手动。

If need to use such a type in a map then you have to avoid the use of operator[] by using find and insert "manually".

这篇关于为什么在STL映射中用作值的类需要在...中使用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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