试图在一个类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;
}
在上面的片段中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
我已经阅读了类似的文章,并且它们都解决了某种编程错误,但是在阅读它们之后,我仍然不确定该错误对我的代码意味着什么。我不仅很好奇如何解决这个问题,而且很好奇为什么在构造函数中使用映射按键分配值的工作效果很好,但是同一过程却无法使运算符重载。
答案 0 :(得分:0)
当您读取错误时,它会告诉您有关该问题的确切信息:
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<...>::operator()(...)
。因此,您要做的是应该参考cppreference之类的参考文献,您会发现没有operator()
。
此外,您会看到有一个 Element Access 部分,其中提供了两个功能:
at
:通过边界检查访问指定的元素operator[]
:访问或插入指定的元素这非常准确地告诉您存在哪些功能。如果您更详细地检查这些内容,还将看到function signature,就像operator[]
一样:
T& operator[]( const Key& key );
T& operator[]( Key&& key );
这意味着您可以将左值的const引用或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