繁体   English   中英

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM