解决矢量的默认构造函数要求
Work around for default constructor requirement of vector?
我正在尝试使用SystemC(用于系统建模的C++库(为系统编写模型。我的设计由三个主要部分组成:Server
、Environment
、People
对象和Robots
。环境和服务器都需要访问系统中的所有机器人。我最初的想法是在Server
和Environment
对象中保留一个Robot
对象的向量(这些对象将传递到每个对象的构造函数中(。但是,vector 类要求对象具有默认构造函数。根据 SystemC 的性质,"模块"没有默认构造函数,因为每个模块都需要有一个名称。此外,我需要传入Robot
向量。对此的常见解决方案是使用指针向量,然后从构造函数初始化向量,如此处所示。但是,Robot
模块还需要在其构造函数中采用其他参数。所以我真的不能嵌套这个技巧。如果有人能为我提供解决这一困境的方法,我将不胜感激。
为了简洁起见,我只发布Server
和Robot
的代码,因为所有模块都遇到同样的问题;如果我能在一个地方修复它,其他的应该遵循。
服务器.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
因此,您可以很好地创建一个空向量,并根据需要填充它,使用所有必需的参数单独构造每个机器人。
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 构造函数默认公共和私有变量
- 类模板构造函数默认参数
- 构造函数默认参数
- C++模板构造函数默认参数
- 在c++中设置构造函数默认值
- c++构造函数默认参数
- C++构造函数默认值头文件