首页 > 解决方案 > 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*或类似的东西,遗憾的是现在无法查找它。

谢谢你。

标签: c++arraysconstructormember-initialization

解决方案


只需聚合初始化数组:

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.


推荐阅读