简体   繁体   English

如何为arg实现具有两种类型之一的类

[英]How to implement a class that has one of either two types for an arg

if I have a c++ class like: 如果我有一个c ++类,例如:

class Student
{ 
    public: 

    string name;
    int assigned_number;      
};

and I want to use either name or number but not both for each instance, is there a way to make this an Or type where only one of them is required? 并且我想在每个实例中使用名称或数字,但不能同时使用两者,是否有一种方法可以使之成为“ Or类型,而只需要其中一个?

If you are using C++17 or above , you can use std::variant from <variant> : 如果您使用的是C ++ 17或更高版本 ,则可以使用<variant> std::variant

#include <iostream>
#include <variant> // For 'std::variant'

class Student
{
public:
    std::variant<std::string, int> name_and_id;
};

int main() {
    Student stud; // Create an instance of student

    // Pass a string and print to the console...
    stud.name_and_id = "Hello world!";
    std::cout << std::get<std::string>(stud.name_and_id) << std::endl;

    // Pass an integer and print to the console...
    stud.name_and_id = 20;
    std::cout << std::get<int>(stud.name_and_id) << std::endl;
}

std::variant is a new addition to C++17 and is intended to replace the unions from C and has exceptions in case of errors... std::variant是C ++ 17的新增功能,旨在替换C中的并集,并且在出现错误的情况下具有异常...

You can use union. 您可以使用联合。

#include <string>

class Student
{
    // Access specifier 
public:
    Student()
    {

    }
    // Data Members
    union
    {
        std::string name;
        int assigned_number;
    };
    ~Student()
    {

    }
};

int main()
{
    Student test;
    test.assigned_number = 10;
    test.name = "10";
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在一种情况下,如何实现具有明显不同的实现的类? - How to implement a class that has a significantly different implementation in one case? 如果 class 有关于两种枚举类型的信息,我如何生成该 class 的唯一对象的详尽列表? - If a class has information about two enum types, how can I generate an exhaustive list of unique objects of that class? 具有可以是两种类型之一的数据成员的类 - Class with data member that can be one of two types 如何在 C++ 中实现可配置位为 0 或 1 的消息 class? - How to implement message class with configurable bit as either 0 or 1 in C++? 如何在 C++ 中为包含多种类型之一的包装器 class 实现多态性? - How can I implement polymorphism in C++ for a wrapper class that will hold one of several types? 如何检查类是否具有默认构造函数(public,protected或private) - How to check if a class has a default constructor, either public, protected or private 函数的参数有两个模板类型,但只关心一个 - Parameter for function has two templated types, but only care about one 由两名成员中的任何一名成员散布 - Hashing by either one of two members &#39;class shape&#39;没有名为&#39;info&#39;的成员,但添加一个也不起作用 - ‘class shape’ has no member named ‘info’ but adding one doesn't work either 如何最好地实现具有相互依赖类型的模板类 - How Best To Implement A Templated Class with Types That Depend On Each Other
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM