簡體   English   中英

如何為arg實現具有兩種類型之一的類

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

如果我有一個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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM