为什么使用[]时,C ++映射类型参数需要一个空构造函数? [英] Why does the C++ map type argument require an empty constructor when using []?
问题描述
另请参见
C ++标准列表和默认构造类型
不是一个主要问题,只是烦人,因为我不想让我的班在没有特定参数的情况下实例化。
Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.
class MyClass
{
public:
MyClass(MyType1 t);
MyType2 &operator[](int index);
}
map<int, MyClass> myMap;
这给我以下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()
.
如果没有默认构造函数,可以使用insert / find函数。
以下示例工作正常:
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 ++映射类型参数需要一个空构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!