为什么使用[]时C ++ map类型参数需要一个空的构造函数? [英] Why does the C++ map type argument require an empty constructor when using []?

查看:348
本文介绍了为什么使用[]时C ++ map类型参数需要一个空的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


另请参阅
http: //stackoverflow.com/questions/695372/c-standard-list-and-default-constructible-types

不是一个大问题,只是讨厌,因为我不希望我的类无需实例化没有特定的参数。

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.

推荐答案

SGI文档引用:


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 object data_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 ++ map类型参数需要一个空的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆