c++ - 使用之前在 if 语句中定义的变量

标签 c++ object

int main() {
    if(i = 0) {
        myclass1 a = "Example1";
    }
    else {
        myclass2 a = "Example2";
    }
    cout << a << endl;
}

我知道一种方法是在 block 之外定义它,但是如果我在检查 i 的条件之前还没有确定 a 的类型怎么办?

最佳答案

如果您能够使用 您可以使用 std::variantstd::any如果您的类型没有公共(public)基类。这些类是任何或指定类型的类型安全容器。 std::variant 的示例如下:

#include <iostream>
#include <string>
#include <variant>

int main() {
    bool input = false;
    std::cin >> input;

    std::variant<int, long, double, std::string> myVariant;
    if(input)
        myVariant = "Example1";
    else
        myVariant = 3.14;

    std::visit([](auto&& arg) { std::cout << arg << std::endl; }, myVariant);
}

而不是 您也可以使用 boost::variantboost::any .

关于c++ - 使用之前在 if 语句中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45753529/

相关文章:

c++ - 如何为 Objective C 编写 C++ 处理类

python - python __new__ 方法如何返回字符串或unicode对象而不是类对象

java - 将java数据对象转换为服务对象

ios - 自定义对象返回 NSDictionary 作为类型

android - 将列表从第一个 Activity 传递到第三个 Activity

c++ - 如何以模块化方式组织源代码

c++ - 未使用的类成员会使代码自行损坏吗?

c++ - 这两种方法有什么区别?

c++ - 在 C/C++ 中检测有符号溢出

javascript - 在 .each 迭代中返回一个对象 - JavaScript