c++ - 如何根据条件选择结构

标签 c++ oop struct polymorphism

我有两个不同的“结构”、“学生”和“员工”。我想根据消息中提到的字符串来选择它。

struct student {
   string name;
   float score;
}

struct employee {
   int id;
   string dep;
}

我收到这样的消息; $ST,16,JOHN,A$EM,16,IT

根据 STEM 之类的关键字,我必须决定要填充哪个结构。

我设法提取了 STEM 这样的类型,但是当我写的时候,

if (type == "ST")
    student x;
else if (type == "EM")
    employee x;
// long code goes on here to sort and populate `struct`

它说 x 未定义。我知道这是错误的,但我无法解开这个谜语。

如何根据条件选择struct

最佳答案

首先,看起来你的范围是错误的。所以 x 可能不可见。

不知道你的代码看起来如何,但你可以定义一个基类,一个在条件之前的指针并通过条件分配内存(我不会那样做)。或者,您需要在正确的范围内工作。

struct base {
    //whatever
};

struct student : public base  {
};
struct employee : public base {
};

base *ptr;
if (type == "ST")
    ptr = new student;
else if (type == "EM")
    ptr = new employee;

关于c++ - 如何根据条件选择结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48769728/

相关文章:

c - 我如何让它编译为 x64

c++ - 访问 2D 结构时程序崩溃

java - C++ 结构到 Java 类

javascript - 在 Javascript 中扩展对象

c++ - 硬件功能的包装器

c++ - 如何保证进程调用malloc()时立即分配物理内存?

c++ - 通过传递指针的地址来初始化 std::unique_ptr

C++类设计题

ios - 在@IBAction 中分配来自不同类的另一个变量?

c++ - 添加新库以编译 anyterm。如何编辑 Makefile?