int main() {
if(i = 0) {
myclass1 a = "Example1";
}
else {
myclass2 a = "Example2";
}
cout << a << endl;
}
我知道一种方法是在 block 之外定义它,但是如果我在检查 i
的条件之前还没有确定 a
的类型怎么办?
最佳答案
如果您能够使用 c++17您可以使用 std::variant
或 std::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);
}
而不是 c++17您也可以使用 boost::variant
或 boost::any
.
关于c++ - 使用之前在 if 语句中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45753529/