[英]Type map… does not provide a call operator
嘗試在 class 月份實現一些重載運算符:
class Month
{
int monthNumber;
string name;
}
我能夠毫無問題地實現以下構造函數:
Month::Month(int cust_month)
{
monthNumber = cust_month;
name = int_month.at(cust_month);
}
請注意使用 map(未顯示) 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
我讀過類似的帖子,他們都解決了某種編程錯誤,但在閱讀之后,我仍然不確定這個錯誤對我的代碼意味着什么。 我不僅很好奇如何解決它,而且很好奇為什么使用 map 在我的構造函數中通過鍵分配值工作正常,但相同的過程無法重載運算符。
當您閱讀錯誤時,它會准確地告訴您問題所在:
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 的 map,它不提供呼叫運算符。 這意味着沒有 function std::map<...>::operator()(...)
。 所以你要做的是你應該 go 到像cppreference這樣的引用,你會看到沒有operator()
。
此外,您會看到有一個Element Access部分,它為您提供兩個功能:
at
:使用邊界檢查訪問指定元素operator[]
: 訪問或插入指定元素這可以非常准確地告訴您存在哪些功能。 如果您更詳細地檢查這些,您還將看到function 簽名,例如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.