Object array initialization without default constructor

后端 未结 11 2096
误落风尘
误落风尘 2020-11-22 04:20
#include 
class Car
{
private:
  Car(){};
  int _no;
public:
  Car(int no)
  {
    _no=no;
  }
  void printNo()
  {
    std::cout<<_no<

        
11条回答
  •  没有蜡笔的小新
    2020-11-22 04:56

    In C++11's std::vector you can instantiate elements in-place using emplace_back:

      std::vector mycars;
    
      for (int i = 0; i < userInput; ++i)
      {
          mycars.emplace_back(i + 1); // pass in Car() constructor arguments
      }
    

    Voila!

    Car() default constructor never invoked.

    Deletion will happen automatically when mycars goes out of scope.

提交回复
热议问题