if语句中的变量范围

tpg*_*114 26 c++ constructor scope

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

考虑以下示例(int仅用于说明这一点):

#include <iostream>

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

  std::cout << i << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

编辑

根据给出的答案,情况更复杂,因此可能必须改变方法.有一个抽象的基类A和两个从A派生的B和C类.如下所示:

if(condition) {
   B obj(args);
} else {
   C obj(args);
}
Run Code Online (Sandbox Code Playgroud)

改变方法?由于A是抽象的,我不能只声明A* obj并创建适当的类型new.

Luc*_*ore 25

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

- 局部变量的范围仅在括号内:

{
   int x; //scope begins

   //...
}//scope ends
//x is not available here
Run Code Online (Sandbox Code Playgroud)

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

如果你不处理指针:

A a( condition ? 1 : 2 );
Run Code Online (Sandbox Code Playgroud)

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

A a = condition ? A(1) : A(2,3);
Run Code Online (Sandbox Code Playgroud)

如果要在堆上创建实例:

A* instance = NULL;
if ( condition )
{
   instance = new A(1);
}
else
{
   instance = new A(2);
}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:

是的你可以:

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

编辑:

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

 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;
    }
 };
Run Code Online (Sandbox Code Playgroud)


Ben*_*ley 5

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

是的。

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

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

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

void bar()
{
    T i(foo());
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

你的意思是?这正是动态类型的工作原理。除了我不会使用原始指针,我会使用 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));
}
Run Code Online (Sandbox Code Playgroud)