C++ if 语句中变量的范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8543167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:45:38  来源:igfitidea点击:

Scope of variables in if statements

c++constructorscope

提问by tpg2114

I have a class that has no default constructor or assignment operator so it is declared and initialized within an if/else statement depending on the result of another function. But then it says that it is out of scope later even though both routes of the conditional will create an instance.

我有一个没有默认构造函数或赋值运算符的类,因此它根据另一个函数的结果在 if/else 语句中声明和初始化。但是后来它说它超出了范围,即使条件的两条路线都将创建一个实例。

Consider the following example (done with intjust to illustrate the point):

考虑以下示例(完成int只是为了说明这一点):

#include <iostream>

int main() 
{
  if(1) {
    int i = 5;
  } else {
    int i = 0;
  }

  std::cout << i << std::endl;
  return 0;
}

Do variables declared in a conditional go out of scope at the end of the conditional? What is the correct way to handle the situation where there is no default constructor but the arguments for the constructor depend on certain conditionals?

条件中声明的变量是否在条件结束时超出范围?处理没有默认构造函数但构造函数的参数取决于某些条件的情况的正确方法是什么?

Edit

编辑

In light of the answers given, the situation is more complex so maybe the approach would have to change. There is an abstract base class A and two classes B and C that derive from A. How would something like this:

根据给出的答案,情况更为复杂,因此可能必须改变方法。有一个抽象基类 A 和两个从 A 派生的类 B 和 C。这样的事情会怎样:

if(condition) {
   B obj(args);
} else {
   C obj(args);
}

change the approach? Since A is abstract, I couldn't just declare A* objand create the appropriate type with new.

改变方法?由于 A 是抽象的,我不能只A* objnew.

回答by Luchian Grigore

"Do variables declared in a conditional go out of scope at the end of the conditional?"

“条件中声明的变量在条件结束时是否超出范围?”

Yes- the scope of a local variable only falls within enclosing brackets:

- 局部变量的作用域仅在括号内:

{
   int x; //scope begins

   //...
}//scope ends
//x is not available here

In your case, say you have class A.

在你的情况下,说你有class A

If you're not dealing with pointers:

如果您不处理指针:

A a( condition ? 1 : 2 );

or if you're using a different constructor prototype:

或者如果您使用不同的构造函数原型:

A a = condition ? A(1) : A(2,3);

If you're creating the instance on the heap:

如果您在堆上创建实例:

A* instance = NULL;
if ( condition )
{
   instance = new A(1);
}
else
{
   instance = new A(2);
}

or you could use the ternary operator:

或者您可以使用三元运算符:

//if condition is true, call A(1), otherwise A(2)
A* instance = new A( condition ? 1 : 2 );

EDIT:

编辑:

Yes you could:

是的,你可以:

A* x = NULL; //pointer to abstract class - it works
if ( condition )
   x = new B();
else
   x = new C();

EDIT:

编辑:

It seems what you're looking for is the factory pattern (look it up):

看来您正在寻找的是工厂模式(查找):

 class A; //abstract
 class B : public A;
 class C : public A;

 class AFactory
 {
 public:
    A* create(int x)
    {
       if ( x == 0 )
          return new B;
       if ( x == 1 )
          return new C;
       return NULL;
    }
 };

回答by Benjamin Lindley

Do variables declared in a conditional go out of scope at the end of the conditional?

条件中声明的变量是否在条件结束时超出范围?

Yes.

是的。

What is the correct way to handle the situation where there is no default constructor but the arguments for the constructor depend on certain conditionals?

处理没有默认构造函数但构造函数的参数取决于某些条件的情况的正确方法是什么?

Write a function that returns a value, from which you copy.

编写一个返回值的函数,从中复制。

T foo()
{
    if(condition)
        return T(x);
    return T(y);
}

void bar()
{
    T i(foo());
}

Edit:

编辑:

Since A is abstract, I couldn't just declare A* obj and create the appropriate type with new.

由于 A 是抽象的,我不能只声明 A* obj 并使用 new 创建适当的类型。

What do you mean? That's exactly how dynamic typing works. Except I wouldn't use a raw pointer, I would use a unique_ptr.

你的意思是?这正是动态类型的工作原理。除了我不会使用原始指针外,我会使用 unique_ptr。

std::unique_ptr<A> obj;
if(condition) {
   obj = std::unique_ptr<A>(new B(args));
} else {
   obj = std::unique_ptr<A>(new C(args));
}

回答by boba-feh

Yes it will be out of scope if declared in a conditional, loop etc. Will the type of the variable change depending on the conditional?

是的,如果在条件、循环等中声明,它将超出范围。变量的类型会根据条件而改变吗?

回答by Dani

Your alternative will be pointers:

您的替代方案将是指针:

MyObject *obj;
if(cond1)
{
    obj = new MyObject(1, 2, 3);
}
else
{
    obj = new MyObject(4, 5);
}

Remember to delete it when you are done with it, or use a smart pointer.

请记住在完成后将其删除,或使用智能指针。