Objects with arguments and array

前端 未结 4 502
轮回少年
轮回少年 2021-01-06 06:36

Is there a way in C++ where an objects has argument added upon it, with an array such as:

int x = 1;
int y = 2;

Object myObject( x, y )[5]; // does not work         


        
相关标签:
4条回答
  • 2021-01-06 07:09

    Or something like this:

    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);
    }
    

    Maybe it's a function with x,y and numObjects as params?

    0 讨论(0)
  • 2021-01-06 07:10

    When constructing an array of objects in C++ only the default constructor can be used unless you're using the explicit Array initialization syntax:

    Object myObject[5] = { Object( x, y ),
                           Object( x, y ),
                           Object( x, y ), 
                           Object( x, y ), 
                           Object( x, y ) }
    

    Here's some good information from the C++ FAQ about this:

    http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.5

    0 讨论(0)
  • 2021-01-06 07:15

    You haven't mentioned which language yet, but in C# 3.0 you can get close with collection initializers:

    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)
    };
    
    0 讨论(0)
  • 2021-01-06 07:16

    If you don't mind using a vector instead of an array:

    std::vector<Object> obj_vec(5, Object(x, y));
    

    Or if you really want an array and don't mind initializing it in 2 steps:

    Object obj_array[5];
    std::fill_n(obj_array, 5, Object(x, y));
    
    0 讨论(0)
提交回复
热议问题