Why does the C++ map type argument require an empty constructor when using []?(为什么 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;
这篇关于为什么 C++ 映射类型参数在使用 [] 时需要一个空的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++ 映射类型参数在使用 [] 时需要一个空
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
