[英]Operator comma in C++ ?: conditional
Could you tell me what's the problem with ?: operator it tells error:你能告诉我有什么问题吗?:操作员告诉错误:
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
The Code:编码:
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;
}
The types of the 2 operands of the conditional operator needs to be the same.条件运算符的两个操作数的类型需要相同。
(A<B) ? (c = 100, B=100, cout << "!!!") : (A = 100);
The type of c = 100, B=100, cout << "!!!"
c = 100, B=100, cout << "!!!"
的类型is the type of cout << "!!!"
是
cout << "!!!"
的类型, which is std::ostream
. ,即
std::ostream
。
The type of of A = 100
is int
. A = 100
的类型是int
。
These 2 types do not match, hence the error.这两种类型不匹配,因此出现错误。
EDIT: The comma operator returns the value of the last part.编辑:逗号运算符返回最后一部分的值。 You cann add an int, for example:
您不能添加一个 int,例如:
(A<B) ? (c = 100, B=100, (cout << "!!!"), 42) : (A = 100);
// ^^^^
If you are going to write obfuscated code, make sure you know how to use casts, as the solution is obviously to cast the result of cout << "!!!"
如果您要编写混淆代码,请确保您知道如何使用强制转换,因为解决方案显然是强制转换
cout << "!!!"
的结果to an int
:到一个
int
:
(A<B) ? (c = 100, B=100, reinterpret_cast<int>(cout << "!!!")) : (A = 100);
As the return value is not being used it might be clearer to cast both sides to void.由于未使用返回值,因此将双方都设为无效可能更清楚。
Although not as clear as just using a good old "if".虽然不如使用一个好的旧“如果”那么清楚。
This is blatant abuse of the ?: operator.这是对 ?: 运算符的公然滥用。 Use an
if
statement.使用
if
语句。 That's what they're for.这就是他们的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.