相关疑难解决方法(0)

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

#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;
}    
Run Code Online (Sandbox Code Playgroud)

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

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

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

c++ arrays constructor

60
推荐指数
6
解决办法
10万
查看次数

标签 统计

arrays ×1

c++ ×1

constructor ×1