我有两个不同的“结构”、“学生”和“员工”。我想根据消息中提到的字符串来选择它。
struct student {
string name;
float score;
}
struct employee {
int id;
string dep;
}
我收到这样的消息; $ST,16,JOHN,A
或 $EM,16,IT
根据 ST
或 EM
之类的关键字,我必须决定要填充哪个结构。
我设法提取了 ST
或 EM
这样的类型,但是当我写的时候,
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/