[英]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.