How do I initialize a stl vector of objects who themselves have non-trivial constructors?

后端 未结 5 1496
悲哀的现实
悲哀的现实 2020-12-07 17:56

suppose I have the following class:

class MyInteger {
private:
  int n_;
public:
  MyInteger(int n) : n_(n) {};
  // MORE STUFF
};

And supp

5条回答
  •  广开言路
    2020-12-07 18:19

    If the elements of the vector are not default-constructible, then there are certain things you cannot do with the vector. You cannot write this (example 1):

    vector foo(10);
    

    You can, however, write this (example 2):

    vector foo(10, MyInteger(37));
    

    (This only requires a copy constructor.) The second argument is an initializer for the elements of the vector.

    In your case, you could also write:

    vector foo(10, 37);
    

    ...since MyInteger has a non-explicit constructor taking "int" as argument. So the compiler will cast 37 to MyInteger(37) and give the same result as example 2.

    You might want to study the documentation on std::vector.

提交回复
热议问题