Can I avoid an ambiguity, when I declare a fixed length vector in class?

后端 未结 2 1227
再見小時候
再見小時候 2021-01-27 03:20

I want to declare a vector of 2 elements as a class member. But next code generates an error:

class A {
private:
   std::vector v (2);
   ...
}
         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-27 04:05

    You can safely use this syntax:

    std::vector v = std::vector(2);
    

    Alternatively, use brace initialization, but you must be careful: the std::initializer_list constructor will be picked, so to initialize a vector with two value- (therefore zero-) initialized ints you need

    std::vector v{0, 0};
    

提交回复
热议问题