如何在C++中实现可以在其他地方使用的具有相同条件的局部变量

vuktfyat  于 2023-02-17  发布在  其他
关注(0)|答案(4)|浏览(132)

如何让下面的代码工作?

int main(){
    bool flag = true;

    if(flag){
        // note that I donot want to define variable globally.
        int a = 5;
    }

    if(flag){
        // but I still want to use this local variable within the same condition.
        a++;
    }
}

注意我不想全局定义这个变量或者使用一个静态变量,我很好奇c++是否有一种方法可以让局部变量在相同条件下在所有区域都可用?

f2uvfpb9

f2uvfpb91#

你所要求的是一个局部变量,而不是一个局部变量,这是不可能的。
另一方面,你基本上想要的是数据+代码,这就是一个类。如果你把它 Package 在一个类中,你的函数可能看起来像这样:

int main(){   
    Foo f;
    f.doSomething();
}

这个类可以是

struct Foo {
   bool flag = false;
   int a = 0;
   void doSomething() {
      if (flag) ++a;
   }
};
fgw7neuy

fgw7neuy2#

你直接请求的东西是不可能的。你必须预先声明一些东西。如果它是关于在你有一些相关细节之前避免构造对象的,你可以使用std::optional

int main()
{
    std::optional<int> a;

    if(flag)
    {
       a = 10;
    }

    if(a)
    {
        *a++;
    }
}
8xiog9wr

8xiog9wr3#

您可以将变量的作用域设置为所需的作用域。

int main(){
    bool flag = true;

    // declare it in this scope if you want it to persist
    // thru this scope
    int a;

    if(flag){
        a = 5;
    }

    if(flag){
        a++;
    }
}
a0x5cqrl

a0x5cqrl4#

没有。
根据section 6.4.3, basic.scope.block
各1件

  • (1.1)选择或迭代语句(stmt.select(https://eel.is/c++draft/stmt.select),[stmt.iter]),
  • [...]
  • (1.4)不是处理程序的复合语句的复合语句([stmt. block])

引入包含该语句或处理程序的块范围。
属于块作用域的变量是块变量。
根据www.example.com、www.example.com第1条: 6.7.5.4 , basic.stc.auto , clause 1:
属于块或参数作用域的变量,并且没有显式声明为static、thread_local或extern,则有自动存储期限。这些实体的存储将持续到创建它们的块退出。

相关问题