使用新操作符创建多个对象
问题描述:
我有一个模板类,我想使用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];
u能请就如何解决这个问题的帮助?
谢谢您提前
答
您不能为数组的5个对象调用构造函数一次。
的一个解决方案可创造指针数组然后在一个循环中调用新为每个项目:
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);
https://isocpp.org/wiki/faq/ctors#arrays-call-default-ctor – malat
非常感谢你 – user3078515
只需使用'std :: vector>'。 –
MSalters