![](/img/trans.png)
[英]What's the precedence of comma operator inside conditional operator in C++?
[英]Operator comma in C++ ?: conditional
你能告訴我有什么問題嗎?:操作員告訴錯誤:
C2446: ':' : no conversion from 'int' to 'std::basic_ostream<_Elem,_Traits>'
c:\documents\visual studio 2005\projects\8.14\8.14\8.14.cpp 36
編碼:
int _tmain(int argc, _TCHAR* argv[])
{
int B;
int A=(6,B=8);
bool c = true;
cout << endl << B;
while (B != 100)
{
cout << "qgkdf\n";
(A<B) ? (c = 100, B=100, cout << "!!!") : (A = 100);
A--;
}
_getch();
return 0;
}
條件運算符的兩個操作數的類型需要相同。
(A<B) ? (c = 100, B=100, cout << "!!!") : (A = 100);
c = 100, B=100, cout << "!!!"
的類型是cout << "!!!"
的類型 ,即std::ostream
。
A = 100
的類型是int
。
這兩種類型不匹配,因此出現錯誤。
編輯:逗號運算符返回最后一部分的值。 您不能添加一個 int,例如:
(A<B) ? (c = 100, B=100, (cout << "!!!"), 42) : (A = 100);
// ^^^^
如果您要編寫混淆代碼,請確保您知道如何使用強制轉換,因為解決方案顯然是強制轉換cout << "!!!"
的結果到一個int
:
(A<B) ? (c = 100, B=100, reinterpret_cast<int>(cout << "!!!")) : (A = 100);
由於未使用返回值,因此將雙方都設為無效可能更清楚。
雖然不如使用一個好的舊“如果”那么清楚。
這是對 ?: 運算符的公然濫用。 使用if
語句。 這就是他們的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.