c++ - C ++:使用另一个类中的参数初始化对象数组
问题描述
我正在尝试创建一个将另一个类的对象数组作为其成员的类。这个“较低”的类构造函数需要一个参数(没有默认的 c-tor),我不知道该怎么做。
In .hpp
class ProcessingElement : public sc_core::sc_module
{
public:
ProcessingElement( sc_core::sc_module_name name );
sc_core::sc_module_name name;
};
In .cpp
ProcessingElement::ProcessingElement( sc_core::sc_module_name name ) : name(name) {
//not relevant
}
和“上层”类:
In .hpp
class QuadPE : public sc_core::sc_module
{
public:
QuadPE( sc_core::sc_module_name name );
ProcessingElement pe[4];
};
In .cpp
QuadPE::QuadPE( sc_core::sc_module_name name ) : pe[0]("PE0"), pe[1]("PE1"), pe[2]("PE2"), pe[3]("PE3") {
//non relevant
}
这显然会产生错误,但我不确定如何修复它。如果可能的话,我想避免使用向量,所以我在 SO 上找到的一些包含向量的解决方案对我来说并不完美。
请注意,sc_core::sc_module_name
是 typedef ofconst char*
或类似的东西,遗憾的是现在无法查找它。
谢谢你。
解决方案
只需聚合初始化数组:
QuadPE::QuadPE( sc_core::sc_module_name name ) : pe{"PE0", "PE1", "PE2", "PE3"} {}
While you may not want to use std::vector
, I still suggest you give std::array
a look. It's an aggregate too, that serves as a thin (zero overhead) wrapper over a c-style array. Nevertheless, it has full value semantics and is a full-featured standard library container. So you may find it less clunky to work with.
推荐阅读
- java - 我在创建 Spring Boot 项目 pom.xml 时首先遇到错误
- angular - 获取 mat-checkbox 的选中值 - Angular Material
- javascript - 为什么我的两个单独的脚本不能在我的 html 文档中串行运行?
- java - 检查 base64 文本是否是有效的 RSA 公钥 (4096)
- java - 我无法远程连接到我的 dropwizard 应用程序
- php - 如何从mysql pdo生成wav文件到dumpfile
- tensorflow - ValueError:获取参数
不能解释为张量 - php - 在 laravel/PHP 中具有相同命名空间的 2 个类
- java - 当我第二次尝试运行 Hello Agent 时,会发生此错误
- wordpress - Google App Engine Docker 容器 502 错误网关