【问题标题】:Map::operator[] always requires a default constructor [duplicate]Map::operator[] 总是需要一个默认的构造函数[重复]
【发布时间】:2021-01-11 09:13:46
【问题描述】:
#include <iostream>
#include <string>
#include <map>
using namespace std;

class x{
  public:
  string s;
  //x(){cout<<"default"<<endl;}
  x(string s=""):s(s){cout<<"mine"<<endl;}
};

int main()
{
  map<int,x> m;
  m.insert(pair<int,x>(1,x("me")));
  cout<<m[1].s<<endl;
}

我知道当元素不存在时 map::operator[] 需要默认 cst,但是

m[1] 在没有默认 cst 的情况下为苹果 clang 中的 x 类给出错误,即使 m[1] 的元素已经存在。为什么?

【问题讨论】:

  • 这就是静态检查的工作原理。
  • 编译器如何知道现有元素?
  • 使用at: m.at(1).s 不需要默认ctor
  • 为了在编译时确定对象存在,编译器需要执行程序,但不先编译就不可能执行程序。
  • @fas 是 map::at c++11 的特性吗?

标签: c++ dictionary default-constructor


【解决方案1】:

我了解 map::operator[] 在元素不存在时需要默认 cst,[...]

这不太正确。

map::operator[] 始终需要默认构造函数,因为该元素可能不存在。它是否真的存在并不重要,因为map&lt;T&gt; 是否有operator[] 已经在编译时决定了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2021-05-25
    • 2017-07-15
    • 2021-10-12
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多