有没有办法在 C++ 中创建既可以保存整数又可以保存字符串的数据类型?

0 c++

有没有办法在 C++ 中创建既可以保存整数又可以保存字符串的数据类型?

例如,创建一个具有名称的数据类型sti,我可以用它定义整数和字符串变量:

sti a = 10; //this is integer
sti b = "Hello"; //and this is string
Run Code Online (Sandbox Code Playgroud)

cse*_*cse 6

您可以使用C++17 功能std::variant来实现此目的。请参阅此链接了解更多信息

以下是代码示例。在这里查看它的工作情况

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

int main()
{
    using sti = std::variant<int, std::string>;
    sti a = 10;
    sti b = "Hello";
    std::cout<<std::get<int>(a) << " | " <<
                std::get<0>(a) <<std::endl; // Same as above
    
    std::cout<<std::get<std::string>(b) << " | " <<
                std::get<1>(b) <<std::endl;// Same as above
    return 0;
}
Run Code Online (Sandbox Code Playgroud)