C++。可以在没有错误的情况下执行此操作:"未在此范围内声明"



c++.可以这样做吗?

if (x>3)
 int foo=10
else
 long foo=10

没有错误:

未在此范围内声明

是的,你可以,使用 std::variant C++17boost::variant .

std::variant<int, long> foo;
if(x > 3)
    foo = 10;
else
    foo = long(10);

然后像这样访问foo

if(auto value = std::get_if<int>(&foo))
    std::cout << "foo is int: " << *value << 'n'; 
else {
    long value = std::get<long>(foo);
    std::cout << "foo is long: " << value << 'n'; 
}

我不知道你为什么要这样做。long保证能够保存所有int值,因此您可以只foo类型 long ,并完全避免std::variant

不,你不能,因为该变量x的作用域在 if 块内,因此您无法从外部看到它:

int main()
{
    if(!x)
        int value = 100;
    else
        double value = 5.57; 
    cout << value << endl; // values is scoped to if statement or else's so it will be destructed
    // this example is like what you have above
    for(;;)
    {
        int a = 77;
        if(a)
            break;
    }
    cout << a << endl; // error a is undeclared identifier
    return 0;
}

最新更新