解决矢量的默认构造函数要求

Work around for default constructor requirement of vector?

本文关键字:构造函数 默认 解决      更新时间:2023-10-16

我正在尝试使用SystemC(用于系统建模的C++库(为系统编写模型。我的设计由三个主要部分组成:ServerEnvironmentPeople对象和Robots。环境和服务器都需要访问系统中的所有机器人。我最初的想法是在ServerEnvironment对象中保留一个Robot对象的向量(这些对象将传递到每个对象的构造函数中(。但是,vector 类要求对象具有默认构造函数。根据 SystemC 的性质,"模块"没有默认构造函数,因为每个模块都需要有一个名称。此外,我需要传入Robot向量。对此的常见解决方案是使用指针向量,然后从构造函数初始化向量,如此处所示。但是,Robot模块还需要在其构造函数中采用其他参数。所以我真的不能嵌套这个技巧。如果有人能为我提供解决这一困境的方法,我将不胜感激。

为了简洁起见,我只发布ServerRobot的代码,因为所有模块都遇到同样的问题;如果我能在一个地方修复它,其他的应该遵循。

服务器.h

#ifndef SERVER_H_
#define SERVER_H_
#include <vector>
#include <systemc.h>
#include "Person.h"
#include "Robot.h"
SC_MODULE (Server)
{
public:
  sc_in<bool> clk;
  SC_HAS_PROCESS(Server);
  Server(sc_module_name name_, std::vector<Robot> robots);
  void prc_server();
};
#endif /* SERVER_H_ */

服务器.cpp

#include "Server.h"
Server::Server(sc_module_name name_, std::vector<Robot> robots) : sc_module(name_)
{
  SC_METHOD(prc_server);
    sensitive << clk.pos();
}

void Server::prc_server()
{
}

机器人.h

#ifndef ROBOT_H_
#define ROBOT_H_
#include <vector>
#include <systemc.h>
#define ROBOT_SPEED 0.1
SC_MODULE (Robot)
{
private:
  std::vector<unsigned> path;
public:
  sc_in<bool> clk;          // system clock
  sc_in<bool> canMove;      // true = safe to move
  sc_in<unsigned> position; // current position
  sc_out<bool> arrived;     // true =  arrived at next position
  SC_HAS_PROCESS(Robot);
  Robot(sc_module_name name_, std::vector<unsigned> path);
  void prc_robot();
};

#endif /* ROBOT_H_ */

机器人.cpp

#include "Robot.h"
Robot::Robot(sc_module_name name_, std::vector<unsigned> path) : sc_module(name_)
{
  this->path = path;
  SC_METHOD(prc_robot);
    sensitive<<clk.pos();
}
void Robot::prc_robot()
{
}

这是编译器输出(我把它放在 pastebin 上,因为我超过了字符数(

环境和服务器都需要访问 系统。我最初的想法是将机器人对象向量保留在 服务器和环境对象(将被传递 进入每个构造函数(。

根据你的陈述,你最初的想法(以及你展示的代码片段(将导致你复制你环境中的所有机器人,因为每个服务器和环境都会保留你的向量的副本。

这不是您打算做的,除非您想添加代码来痛苦地同步每个对象中的重复机器人。

因此,您最好管理机器人的共享向量,并在构建时将其传递给您的系统/环境/等。通过引用。 那么你将只有一个单一且一致的机器人向量。如果在一个位置更新,则所有其他对象也将看到更新。

现在,矢量不需要默认构造器。 这取决于您执行的操作:

vector<Robot> robots;        // legal: empty vector, not a single robot constructed
//vector<Robot> robts(10);   // ilegal:  requires default constructor to initializethe 10 elements
robots.push_back(a);         // legal:  a robot was created, it is now copied into the vector  
robots.reserve(10);          // legal:  space is allocated for 10 reobots, but no robot is actually constructed. 
robots.resize(10);           // illegal:  space is allocated and robots are created to 

因此,您可以很好地创建一个空向量,并根据需要填充它,使用所有必需的参数单独构造每个机器人。