带有多个参数的 static_cast 是怎么回事?
谁能告诉我这个演员有什么效果(除了将 happyNumber 设置为 1337 之外),如果有的话,如果没有其他效果,我怎么能写这样的代码??? 这是编译器错误,还是 C++ 的某些“隐藏功能”?
int happyNumber = static_cast<int>(123.456, TRUE, "WTF" , false , "IS" , NULL , "GOING" , 0xff , "ON???" , 1337);
我很惊讶这竟然能编译。 我通过一个错误发现了它,我不小心将第二个参数设置为要进入正在转换的表达式的函数调用中的参数。 这导致了一个严重的错误,即从第二个参数转换对象,仅使用一个参数调用该函数。 它编译...并且最初并没有繁荣...
我正在使用 Microsoft Visual C++ 2008。
Can anyone tell me what this cast has for effect (besides setting happyNumber to 1337), if any at all, and if it has no other effect, how come I can write code like this??? Is this a compiler bug, or some "hidden away feature" of C++?
int happyNumber = static_cast<int>(123.456, TRUE, "WTF" , false , "IS" , NULL , "GOING" , 0xff , "ON???" , 1337);
I was surprised this would compile at all. I found it through a bug where I accidentally set the second parameter to something that was meant to go in a function call of the expression being cast. This resulted in a nasty bug where the object was cast from the second parameter, calling the function with only one argument. It compiled... And didn't initially boom...
I am using Microsoft Visual C++ 2008.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态转换采用一个参数,但其参数是一个表达式,并且表达式可以包含逗号运算符。 逗号用于您想要同时计算两个或多个表达式的副作用的情况,例如:
它有点用,因为如果没有它,您只能为 for 循环的初始值设定项、条件和继续部分分别计算一个表达式 (或任何其他需要表达式的地方)。 不过,它通常不会产生最清晰的代码,而且语义也很奇怪。 正如您所观察到的,逗号分隔的序列的计算结果是其最后一个表达式的值。
Static cast takes one argument, but its argument is an expression, and expressions can include the comma operator. Comma is used in situations where you want to evaluate two or more expressions at once for their side effects, e.g.:
It's somewhat useful because without it you could only evaluate one expression each for the initializer, condition, and continue parts of the for loop (or any other place an expression is expected). It doesn't usually make for the clearest code, though, and the semantics are odd. As you observed, a comma-separated sequence evaluates to the value of its last expression.