如何从另一个结构为结构赋值?

时间:2021-03-09 13:34:13

标签: c++ xcode

我有两个结构如下:

 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;
 

我的问题是我无法为“job”结构中的“tasks”赋值,但使用“command”结构的变量。

1 个答案:

答案 0 :(得分:1)

我建议不要使用指向 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 };

godbolt

如果您想继续使用您的指针并且您是 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));
     }
相关问题