7
下面是用作地圖的價值類:爲什麼在STL映射中用作值的類需要在...中使用默認構造函數?
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進行編譯。
確切地說,'operator []'不分配,但返回對新創建值的引用。分配是用戶代碼。 – 2010-02-27 09:58:08
@dribeas:是的,沒錯。我將更新爲學者! – 2010-02-27 10:09:15