为什么 C++ 映射类型参数在使用 [] 时需要一个空的构造函数?
另见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;
相关文章