8

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 ) { }

};

Inside main():

map< int, Book > mapBooks;

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

The statement causing the error is:

mapBooks[ i ] = b;

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.

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

4

1 回答 1

12

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

在之前不存在条目的情况下,条目的一半值需要在分配之前默认构造。这只是接口需要工作以与条目已经存在的情况保持一致的方式。

如果需要在地图中使用这种类型,那么您必须避免使用operator[]by usingfindinsert“手动”。

于 2010-02-27T09:29:34.987 回答