作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在 C++ 中,您可以在 if 语句中初始化变量,如下所示:
if (CThing* pThing = GetThing())
{
}
为什么人们会认为这种风格不好或好?有什么好处和坏处?
我个人喜欢这种风格,因为它限制了 pThing 变量的范围,所以当它为 NULL 时永远不会被意外使用。但是,我不喜欢你不能这样做:
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
如果有办法使上述工作,请张贴。但如果那是不可能的,我还是想知道为什么。
最佳答案
重要的是 C++ 中的声明不是表达式。
bool a = (CThing* pThing = GetThing()); // not legit!!
您不能在 if 语句中同时进行声明和 bool 逻辑,C++ 语言规范明确允许表达式或声明。
if(A *a = new A)
{
// this is legit and a is scoped here
}
我们如何知道表达式中的一个术语和另一个术语之间是否定义了a?
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
咬紧牙关,使用内部 if。范围规则很有用,您的逻辑很明确:
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
关于c++ - 赞成/反对 : Initializing a variable in a conditional statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/136548/
我是一名优秀的程序员,十分优秀!