如何实现具有两种类型的类之一的类
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;
}
相关文章:
- C++ 一个函数,可以根据接受的值返回两种类型之一
- C++指针中的这两种类型的值分配有什么区别?
- C++两种类型相互依赖
- 两种类型的构造函数重载
- 没有使用两种类型的字符串进行匹配的函数调用
- 声明具有两种类型的变量:"int char"
- 键入来自不同第三方库的两种类型,无需联合
- 给定这两种类型,我是否可以确定虚拟函数是否已被覆盖?
- 如何在任何两种类型之间reinterpret_cast
- 如何检查两种类型是否相同,忽略const和参考
- 比较两种类型的多组以保持平等
- 这两种类型的结构的写法是一样的吗?
- 两种类型转换有何不同?
- 两种类型的定义构造函数有什么区别?第一个使用":",第二个用大括号(如函数)定义它
- 当两种类型相同时,专用于 C++ 模板函数
- 检查两种类型是否属于同一模板
- 模板结构可容纳两种类型,但当时只有一种
- 如何实现具有两种类型的类之一的类
- 如何在 Cython 中将C++中的模板化函数用于两种类型
- 穿越拥有两种类型值的BST