![](/img/trans.png)
[英]error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’
[英]no match for 'operator+=' (operand types are 'std::basic_ostream<char>' and 'int')
鑒於以下代碼;
#include<iostream>
using namespace std;
int main(){
int number_1 = 3;
int result_1 = 10;
result_1 += number_1;
cout << ++result_1;
cout << result_1 += number_1;
}
行cout << result_1 += number_1;
給我一個錯誤。
'operator+=' 不匹配(操作數類型是 'std::basic_ostream' 和 'int')
另一方面, cout << ++result_1;
運行沒有任何問題。
誰能解釋一下錯誤是什么,原因是什么?
- 誰能解釋一下錯誤是什么,原因是什么?
根據Operator Precedence , operator<<
優先級高於operator+=
,因此您的代碼等效於:
(cout << result_1) += number_1;
而cout << result_1
將返回std::cout
(即std::ostream&
),然后嘗試在std::ostream
上調用operator+=
並且它不存在。 這就是錯誤消息試圖告訴您的內容。
您可以將其更改為:
cout << (result_1 += number_1) ;
或者從根本上避免這種令人困惑的代碼。
result_1 += number_1;
cout << result_1;
- 另一方面
cout << ++result_1;
運行沒有任何問題。
因為operator++
比operator<<
具有更高的優先級。 所以它相當於cout << (++result_1);
會沒事的。
如果您查看運算符優先級規則,您會發現該語句等效於
(cout << result_1) += number_1 ;
operator<<
返回std::cout
。 並且不存在std::ostream::operator+=(int)
。
解決方案:使用括號來表達預期的操作順序。
另一方面 cout << ++result_1; 運行沒有任何問題
正如人們所料。 研究運算符的優先級。
運算符優先級。
該調用在語義上等同於cout << result_1; cout += result;
類的東西cout << result_1; cout += result;
cout << result_1; cout += result;
- 這是無效的。
在代碼中添加括號(允許在<<
之前計算+=
)如下允許代碼編譯;
cout << (result_1 += number_1);
關於錯誤本身; 編譯器無法為提供的參數找到operator +=
實現 - 沒有標准的實現。 這是因為cout << result_1
在operator +=
之前被評估。 從上面可以看出,這是有道理的,但並不能立即表明可以應用潛在修復的位置。
仔細閱讀你的編譯器錯誤。 一切都在那里 :) 。
錯誤的原因是運算符優先級。
編譯器首先執行cout << result_1
。
然后,它嘗試執行如下操作: cout += number_1
。
它有任何意義嗎?
做你打算改變你的線路:
cout << (result_1 += number_1);
我強烈建議閱讀: http : //en.cppreference.com/w/cpp/language/operator_precedence
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.