Object array initialization without default constructor

后端 未结 11 1951
误落风尘
误落风尘 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 05:01

    You can use in-place operator new. This would be a bit horrible, and I'd recommend keeping in a factory.

    Car* createCars(unsigned number)
    {
        if (number == 0 )
            return 0;
        Car* cars = reinterpret_cast(new char[sizeof(Car)* number]);
        for(unsigned carId = 0;
            carId != number;
            ++carId)
        {
            new(cars+carId) Car(carId);
        }
        return cars;
    }
    

    And define a corresponding destroy so as to match the new used in this.

提交回复
热议问题