使用新操作器创建多个对象

Multiple Object creation using new operant

本文关键字:对象 创建 操作器      更新时间:2023-10-16

>我有一个模板类,我想使用 new 运算符创建该类的多个对象,但我似乎无法使其工作。这就是我尝试创建对象的方式

Penalty<GraphType, AltGraph> *penalty = new  Penalty<GraphType, AltGraph>( G, AG, algTimestamp, maxNumDecisionEdges + offset)[5];

我得到的错误是

penalty.cpp:343:130: error: expected ‘,’ or ‘;’ before ‘[’ token
     Penalty<GraphType, AltGraph> *penalty = new  Penalty<GraphType, AltGraph>( G, AG, algTimestamp, maxNumDecisionEdges + offset)[5];

你能帮忙解决这个问题吗?

提前谢谢你

不能为数组的 5 个对象调用一次构造函数。

一种解决方案可能是创建一个指针数组,然后为循环中的每个项目调用 new:

Penalty<GraphType, AltGraph> **penalty = new Penalty<GraphType, AltGraph>*[5];
for (int i = 0; i < 5; i++)
    penalty[i] = new Penalty<GraphType, AltGraph>( G, AG, algTimestamp, maxNumDecisionEdges + offset);