gpt4 book ai didi

c++ - 接受并识别任何类型的输入 C++

转载 作者:行者123 更新时间:2023-11-28 06:02:55 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的 C++ 程序来创建链表。我想让这个列表能够在其容器中存储任何类型的数据。但是,我意识到我的主要问题是能够接受任何类型的输入并存储它。例如,如果变量std::cin 存储的是字符串类型,则只接受字符串,并且该变量必须在程序编译之前定义。

我的问题是:是否有任何方法可以使用 std::cin(或任何其他输入法)接受任何类型的输入,然后根据输入的类型调用某些函数?

符合逻辑的东西......

cin >> data

if (data.type == string)
{
cout << "data's type: string"
}

if (data.type == int)
{
cout << "data's type: int"
}

谢谢!

最佳答案

C++(大部分)是静态类型。也就是说,变量的类型必须在编译时知道并且不能在运行时更改,例如取决于一些用户输入。

这个规则的一个异常(exception)是多态类:当你有一个带有一些 virtual 成员函数的基类时,就会有一种方法(很可能是一个指针作为所有实例的成员该类)以区分该类(及其自身)的子类:

struct Base {
virtual ~Base() {}
};
struct SubA : public Base {};
struct SubB : public Base {};

// ...

Base const & instance = SubA{};
try {
SubA const & as_subA = dynamic_cast<SubA const &>(instance);
// The instance is a SubA, so the code following here will be run.
} catch (std::bad_cast const &) { /* handle that somehow */ }

使用这种机制,或者最好是使用虚拟函数本身,您可以根据实例的动态类型 实现不同的行为,这仅在运行时才知道。

C++ 是一种灵活的语言,您当然可以自己实现类似的东西:

struct Thing {
enum class Type {
Integer, String, Vector
} type;
union {
int integer;
std::string string;
std::vector<int> vector;
} data;
// Plus a lot of work in constructors, destructor and assignment, see rule of 5
};

使用这样的东西可以让你拥有具有动态性质“类型”的对象,并且能够根据对象在运行时实际具有的类型来做不同的事情。

当然你不需要自己写(though its not that hard),有很多实现,例如boost::anyboost::variant .

关于c++ - 接受并识别任何类型的输入 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32926246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com