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

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

问题描述


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

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