为什么 C++ 映射类型参数在使用 [] 时需要一个空的构造函数?

2023-01-21C/C++开发问题
2

本文介绍了为什么 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 object data_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++ 映射类型参数在使用 [] 时需要一个空的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6