没有默认构造函数的对象数组初始化 [英] Object array initialization without default 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;
}
我想创建一个汽车数组,但出现以下错误:
I want to create a car array but I get the following error:
cartest.cpp: In function ‘int main()’:
cartest.cpp:5: error: ‘Car::Car()’ is private
cartest.cpp:21: error: within this context
有没有办法在不公开 Car() 构造函数的情况下进行初始化?
is there a way to make this initialization without making Car() constructor public?
推荐答案
没有.
但是你看!如果您使用 std::vector<Car>
,就像您应该使用的那样(永远不要使用 new[]
),那么您可以准确指定应该如何构造元素*.
But lo! If you use std::vector<Car>
, like you should be (never ever use new[]
), then you can specify exactly how elements should be constructed*.
*好吧.您可以指定要复制的值.
*Well sort of. You can specify the value of which to make copies of.
像这样:
#include <iostream>
#include <vector>
class Car
{
private:
Car(); // if you don't use it, you can just declare it to make it private
int _no;
public:
Car(int no) :
_no(no)
{
// use an initialization list to initialize members,
// not the constructor body to assign them
}
void printNo()
{
// use whitespace, itmakesthingseasiertoread
std::cout << _no << std::endl;
}
};
int main()
{
int userInput = 10;
// first method: userInput copies of Car(5)
std::vector<Car> mycars(userInput, Car(5));
// second method:
std::vector<Car> mycars; // empty
mycars.reserve(userInput); // optional: reserve the memory upfront
for (int i = 0; i < userInput; ++i)
mycars.push_back(Car(i)); // ith element is a copy of this
// return 0 is implicit on main's with no return statement,
// useful for snippets and short code samples
}
具有附加功能:
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i < length; i++) // whitespace! :)
std::cout << cars[i].printNo();
}
int main()
{
// ...
printCarNumbers(&mycars[0], mycars.size());
}
注意 printCarNumbers
确实应该设计不同的,以接受表示一个范围的两个迭代器.
Note printCarNumbers
really should be designed differently, to accept two iterators denoting a range.
这篇关于没有默认构造函数的对象数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文