c++ - 没有默认构造函数的对象数组初始化

标签 c++ arrays constructor

#include <iostream>
class Car
{
private:
  Car(){};
  int _no;
public:
  Car(int no)
  {
    _no=no;
  }
  void printNo()
  {
    std::cout<<_no<<std::endl;
  }
};
void printCarNumbers(Car *cars, int length)
{
    for(int i = 0; i<length;i++)
         std::cout<<cars[i].printNo();
}

int main()
{
  int userInput = 10;
  Car *mycars = new Car[userInput];
  for(int i =0;i < userInput;i++)
         mycars[i]=new Car[i+1];
  printCarNumbers(mycars,userInput);
  return 0;
}    

我想创建一个汽车阵列,但出现以下错误:

cartest.cpp: In function ‘int main()’:
cartest.cpp:5: error: ‘Car::Car()’ is private
cartest.cpp:21: error: within this context

有没有办法在不公开 Car() 构造函数的情况下进行此初始化?

最佳答案

您可以像这样使用 placement-new:

class Car
{
    int _no;
public:
    Car(int no) : _no(no)
    {
    }
};

int main()
{
    void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
    Car *ptr = static_cast<Car *>(raw_memory);
    for (int i = 0; i < NUM_CARS; ++i) {
        new(&ptr[i]) Car(i);
    }

    // destruct in inverse order    
    for (int i = NUM_CARS - 1; i >= 0; --i) {
        ptr[i].~Car();
    }
    operator delete[](raw_memory);

    return 0;
}

来自 More Effective C++ 的引用 - Scott Meyers:
第 4 条 - 避免不必要的默认构造函数

关于c++ - 没有默认构造函数的对象数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570607/

相关文章:

C++ - 将带有引用的长参数列表重构为结构体

PHP 脚本似乎不起作用

ruby-on-rails - Ruby 中的简单自定义范围

c# - C#中的构造函数和继承问题

c++ - 如何在 C++ 编译器不智能的情况下实现 GLSL vec* 构造语法?

c# - C#中的多级继承构造函数

c++ - 使用 DLL 时在应用程序中包含 .lib 文件

c++ - Visual Studio 2015,C++ 项目, fatal error c1510

c++ - 我可以为 C++ 局部变量地址做哪些假设

javascript - 使用 Array.reduce() 从获取 promise 中提取 JSON 数据