在“if”中的变量赋值条件 [英] Variable assignment in "if" condition
本文介绍了在“if”中的变量赋值条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近刚忘了在我的代码中导致一个错字造成的错误:
I recently just lost some time figuring out a bug in my code which was caused by a typo:
if(a=b)
而不是:
if(a==b)
是任何特殊情况下,你会想要分配一个变量在 if
语句中,或者如果不是,为什么编译器不会引发警告或错误? / p>
I was wondering if there is any particular case you would want to assign a value to a variable in a if
statement, or if not, why doesn't the compiler throw a warning or an error ?
推荐答案
if (Derived* derived = dynamic_cast<Derived*>(base)) {
// do stuff with `derived`
}
引用为反模式(使用虚拟分派!),有时 Derived
类型具有 Base
根本不是(因此,不同的功能),这是一个好的方式来打开那个语义差异。
Though this is oft cited as an anti-pattern ("use virtual dispatch!"), sometimes the Derived
type has functionality that the Base
simply does not (and, consequently, distinct functions), and this is a good way to switch on that semantic difference.
这篇关于在“if”中的变量赋值条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文