gpt4 book ai didi

c++ - 如何在 C++ 中使用可以具有多种数据类型的单个变量

转载 作者:行者123 更新时间:2023-12-02 02:50:27 25 4
gpt4 key购买 nike

一个变量怎么可以有两种数据类型?如果“月”是一个变量,它应该从 std::cin 的输入中获取。我应该怎么做才能让用户输入像“January”这样的字符串或像 1 这样的整数?

最佳答案

在 C++ 17 中,我们得到了名为 std::variant 的东西,它基本上是一个类型安全的 union 要使用它,您只需声明您需要的类型:

std::variant<int, std::string> data;

data = "Hello!";
data = 13;
// No Compilation Issues

困难的部分是当您想要检索数据时

std::string& text = std::get<std::string>(data):
int& number = std::get<int>(data);

但请确保您定义的最后一个内容是您尝试检索含义的类型:

data = 13;
std::string& text = std::get<std::string>(data); // Bad Exception Error

更好的办法是使用 std::get_if

if (auto temp = std::get_if<std::string>(&data);
std::string& text = *temp; // do what ever you want

我希望这能回答您的问题,祝您编码愉快!

关于c++ - 如何在 C++ 中使用可以具有多种数据类型的单个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62079146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com