![](/img/trans.png)
[英]is there a way to initialize an array of objects that is inside of the private section of another class using the constructor of that class?
[英]Initialize array of class objects in constructor of another class
如果我有课:
class A
{
private:
char z;
int x;
public:
A(char inputz, int inputx);
~A() {}
}
我想在B
类中创建一个A
数组。
class B
{
private:
A arrayofa[26];
public:
B();
~B() {}
void updatearray(); // This will fill the array with what is needed.
}
class B
{
B:B()
{
updatearray();
std::sort( &arrayofa[0], &arrayofa[26], A::descend );
}
}
如何在B
的构造函数中显式初始化arrayofa
?
将自动调用默认构造函数(对于非POD)。 如果你需要一个不同的构造函数,你运气不好,但你可以使用vector
来支持你需要的东西。
你不能。
数组中的每个元素都将由默认构造函数(无参数构造函数)初始化。
最好的选择是使用矢量。
在这里,您指定一个值,该值将被复制到向量的所有成员中:
class B
{
private:
std::vector<A> arrayofa;
public:
B()
: arrayofa(26, A(5,5))
// create a vector of 26 elements.
// Each element will be initialized using the copy constructor
// and the value A(5,5) will be passed as the parameter.
{}
~B(){}
void updatearray();//This will fill the array with what is needed
}
首先应该有一个class A
的默认构造函数,否则B()
将不会编译。 它将尝试在构造函数体开始执行之前调用class B
成员的默认构造函数。
你可以像这样初始化arrayofa
:
void B::updatearray()
{
arrayofa[0] = A('A', 10);
arrayofa[1] = A('B', 20);
...
}
使用std::vector
代替数组会更好。
std::vector<A> v(26, A('a', 10)); //initialize all 26 objects with 'a' and 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.