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

时间:2014-12-03 22:02:02

标签: c++ vector constructor systemc

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

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

server.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_ */

server.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()
{

}

robot.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_ */

robot.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()
{

}

Here's the compiler output(我把它放在了pastebin上因为我超过了字符数)

1 个答案:

答案 0 :(得分:2)

  

环境和服务器都需要访问到所有机器人中   系统。我最初的想法是保留一个Robot对象的向量   两者 Server和Environment对象(将被传递   进入每个人的构造者。

根据您的陈述,您最初的想法(以及您展示的代码片段)会让您重复环境中的所有机器人,因为每个服务器和环境都会保留您向量的COPY。

除非您想添加代码以痛苦地同步每个对象中的重复机器人,否则您不希望这样做。

因此,您可以更好地管理机器人的共享矢量,并将其在构造中传递给您的系统/环境/等。参考。那么你只有一个单一且一致的机器人矢量。如果在一个地方更新,则所有其他对象也会看到更新。

现在,vector不需要默认的consturctor。这取决于你的操作:

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 

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

相关问题