gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:01:01 25 4
gpt4 key购买 nike

See also C++ standard list and default-constructible types

不是主要问题,只是烦人,因为我不希望我的类在没有特定参数的情况下被实例化。

#include <map>

struct MyClass
{
MyClass(int t);
};

int main() {
std::map<int, MyClass> myMap;
myMap[14] = MyClass(42);
}

这给了我以下 g++ 错误:

/usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’

如果我添加一个默认构造函数,这编译得很好;我确定这不是由不正确的语法引起的。

最佳答案

此问题与 operator[] 相关。引用自 SGI 文档:

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().

如果您没有默认构造函数,您可以使用插入/查找函数。以下示例工作正常:

myMap.insert( std::map< int, MyClass >::value_type ( 1, MyClass(1) ) );
myMap.find( 1 )->second;

关于c++ - 为什么 C++ 映射类型参数在使用 [] 时需要一个空的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com