gpt4 book ai didi

c++ - 赞成/反对 : Initializing a variable in a conditional statement

转载 作者:IT老高 更新时间:2023-10-28 22:17:34 25 4
gpt4 key购买 nike

在 C++ 中,您可以在 if 语句中初始化变量,如下所示:

if (CThing* pThing = GetThing())
{
}

为什么人们会认为这种风格不好或好?有什么好处和坏处?

我个人喜欢这种风格,因为它限制了 pThing 变量的范围,所以当它为 NULL 时永远不会被意外使用。但是,我不喜欢你不能这样做:

if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}

如果有办法使上述工作,请张贴。但如果那是不可能的,我还是想知道为什么。

Question borrowed from here, similar topic but PHP.

最佳答案

重要的是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com