問題描述
另見C++ 標準列表和默認構造類型
不是大問題,只是煩人,因為我不希望我的類在沒有特定參數的情況下被實例化.
Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.
#include <map>
struct MyClass
{
MyClass(int t);
};
int main() {
std::map<int, MyClass> myMap;
myMap[14] = MyClass(42);
}
這給了我以下 g++ 錯誤:
This gives me the following g++ error:
/usr/include/c++/4.3/bits/stl_map.h:419: 錯誤:沒有匹配的函數調用‘MyClass()’
/usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’
如果我添加一個默認構造函數,這編譯得很好;我確定這不是由錯誤的語法引起的.
This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.
推薦答案
此問題來自 operator[].引用自 SGI 文檔:
This issue comes with operator[]. Quote from SGI documentation:
data_type&operator[](const key_type& k)
- 返回對象的引用與特定的鑰匙.如果地圖還沒有包含這樣一個對象,operator[]
插入默認對象data_type()
.
data_type& operator[](const key_type& k)
- Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object,operator[]
inserts the default objectdata_type()
.
如果您沒有默認構造函數,您可以使用插入/查找函數.以下示例工作正常:
If you don't have default constructor you can use insert/find functions. Following example works fine:
myMap.insert( std::map< int, MyClass >::value_type ( 1, MyClass(1) ) );
myMap.find( 1 )->second;
這篇關于為什么 C++ 映射類型參數在使用 [] 時需要一個空的構造函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!