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

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

本文关键字:两种 类型 何实现 实现      更新时间:2023-10-16

如果我有一个C 类,则如下:

class Student
{ 
    public: 
    string name;
    int assigned_number;      
};

我想使用名称或数字,但在每个实例中都不同时使用,是否有一种方法可以使其成为Or类型,其中只需要其中一个?

如果 您正在使用 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是C 17的新补充,旨在替换C中的工会,如果发生错误,则有例外...

您可以使用联合。

#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;
}