为什么在 STL 映射中用作值的类需要...中的默认构造函数?

发布于 2024-08-23 07:52:07 字数 511 浏览 3 评论 0原文

下面是用作映射中的值的类:

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 < 10; ++i )
{
    Book b( i );
    mapBooks[ i ] = b;
}

导致错误的语句是:

mapBooks[ i ] = b;

如果我添加默认构造函数,则不会出现错误。但是,我不明白为什么需要。谁能解释一下吗?如果我使用insert(),则不会出现该问题。

顺便说一下,我使用的是Visual C++ 2008来编译。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光无声 2024-08-30 07:52:07

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

如果条目之前不存在,则在分配之前需要默认构造条目的一半值。这正是界面需要与条目已存在的情况保持一致的工作方式。

如果需要在地图中使用此类类型,则必须通过“手动”使用 findinsert 来避免使用 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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文