【问题标题】:Type map.... does not provide a call operator类型映射.... 不提供呼叫操作员
【发布时间】:2020-04-14 02:08:26
【问题描述】:

尝试在 Month 类上实现一些重载运算符:

class Month
{
      int monthNumber;
      string name;
}

我能够毫无问题地实现以下构造函数:

Month::Month(int cust_month) 
{
    monthNumber = cust_month;
    name = int_month.at(cust_month);
}

注意使用映射(未显示)int_month,其中 int 1-12 映射到相应的月份名称,这很好用。但是在重载 ++ 运算符时尝试做类似的事情:

Month Month::operator++() {
    if (monthNumber == 12) {
        monthNumber = 1;
        name = "January";
    }
    else{
        ++monthNumber;
        name = int_month(monthNumber); // ERROR

    }
    return *this;
}

在上面sn -p int_month 高亮显示并显示错误:

Type 'map<int, std::__1::string>' (aka 'map<int, basic_string<char, char_traits<char>, allocator<char> > >') does not provide a call operator

我读过类似的帖子,他们都解决了某种编程错误,但在阅读之后,我仍然不确定这个错误对我的代码意味着什么。我不仅很好奇如何解决它,而且很好奇为什么在我的构造函数中使用映射按键分配值工作正常,但相同的过程不能重载运算符。

【问题讨论】:

  • 你的意思是.at(),而不是()
  • 好吧,如果您比较在构造函数中分配它的方式与++ 重载的方式,您会发现一些差异。你真的必须在 C++ 中注意所有细节。每一个可能的细节都很重要。附言您的 ++ 运算符应该返回一个引用。

标签: c++ stl operator-overloading


【解决方案1】:

当您阅读错误时,它会准确地告诉您问题所在:

Type 'map<int, std::__1::string>' (aka 'map<int, basic_string<char, char_traits<char>, allocator<char> > >') does not provide a call operator

您有一个从 int 到 string 的映射,它不提供调用运算符。这意味着没有函数std::map&lt;...&gt;::operator()(...)。所以你要做的是,你应该去像cppreference这样的引用,你会看到没有operator()

进一步,您会看到有一个元素访问部分,它为您提供了两个功能:

  • at: 使用边界检查访问指定元素
  • operator[]:访问或插入指定元素

这会非常准确地告诉您存在哪些功能。如果您查看更多详细信息,您还会看到function signature,例如operator[]

T& operator[]( const Key& key );
T& operator[]( Key&& key );

这意味着您可以将右值或对左值的 const 引用传递给括号运算符。还要仔细阅读最后的文档和代码示例,以意识到如果值尚不存在,则将值插入到 map 中(与 at 相反,如果元素不存在则会抛出)。

最后,一些用法示例:

std::map<int, std::string> m;
m[3] = "a"; // inserts "a" at position 3
std::cout << m[3]; // prints "a"
m[3] = "b"; // modifies the conetent at 3 to "b"
std::cout << m[3]; // prints "b"

m.at(3) = "c"; // modifies the content at 3 to "c"
std::cout << m[3]; // prints "b"

m.at(4) = "d"; // this will throw std::out_of_range

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2016-04-08
    • 2014-07-04
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多