c++ - 如何从另一个结构为结构赋值?
问题描述
我有两个结构如下:
struct command{
string name;
int time;
};
struct job{
queue<command*> tasks;
int ID = 0;
jobState *table = NULL;
int time = 0;
};
现在我想为我的结构赋值:到目前为止我所做的是:
job a;
a.time = 20;
a.ID = 2;
我的问题是我无法为“作业”结构中的“任务”赋值,但使用“命令”结构的变量。
解决方案
我建议不要使用指向的指针,command
因为结构相当简单。
#include <queue>
#include <string>
#include <deque>
struct command{
std::string name;
int time;
};
struct jobState {} *jobtable = nullptr;
struct job{
std::queue<command> tasks;
int ID = 0;
jobState *table = NULL;
int time = 0;
void AddCmd(std::string name, int t) {
tasks.push(command {name, t});
}
};
或者如果你想一次分配所有这样的东西可以工作
std::queue<command> x {{{ "Clean up", 42 }, { "A mess", 63}}};
job a { std::move(x), 2, jobtable, 20 };
如果您想继续使用您的指针并且您是 the 的所有者,command
那么您应该使用std::unique_pointer
它应该是这样的
queue<std::unique_ptr<command>> tasks;
...
auto AddCmd(const std::string& name, int time) {
return tasks.emplace(std::make_unique(name, time));
}