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

时间:2016-03-15 11:13:24

标签: c++

我有一个模板类,我想使用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];

请问如何解决这个问题?

提前谢谢

1 个答案:

答案 0 :(得分:0)

您无法为数组的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);