在C ++中是否存在一种方法,其中对象上添加了参数,其中包含如下数组:
int x = 1;
int y = 2;
Object myObject( x, y )[5]; // does not work
我希望我可以将参数放入对象中,同时创建其中5个对象的数组,有谁知道如何?并且有一种不可思议的方式吗?
答案 0 :(得分:7)
在C ++中构造对象数组时,除非使用显式数组初始化语法,否则只能使用默认构造函数:
Object myObject[5] = { Object( x, y ),
Object( x, y ),
Object( x, y ),
Object( x, y ),
Object( x, y ) }
以下是C ++常见问题解答中的一些很好的信息:
答案 1 :(得分:1)
如果您不介意使用向量而不是数组:
std::vector<Object> obj_vec(5, Object(x, y));
或者,如果你真的想要一个数组,不介意分两步进行初始化:
Object obj_array[5];
std::fill_n(obj_array, 5, Object(x, y));
答案 2 :(得分:0)
您尚未提及哪种语言,但在C#3.0中,您可以使用集合初始值设定项:
var myObject = new List<Object>() {
new Object(x,y),
new Object(x,y),
new Object(x,y),
new Object(x,y),
new Object(x,y)
};
答案 3 :(得分:0)
或类似的东西:
int x = 1;
int y = 2;
int numObjects = 5;
Object myObjectArray[numObjects];
for (int i=0, i<numObjects, i++) {
myObjectArray[i] = new myObject(x,y);
}
也许这是一个x,y和numObjects作为params的函数?