在另一个类的构造函数中初始化一个类对象数组

6
如果我有一个类:
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数组?


在构造函数中创建对象通常不是一个好主意。你的目标到底是什么? - Corbin
A::descend是什么?按降序排序的常规方法是为类定义正常比较运算符,然后使用std::greater - Karl Knechtel
3个回答

3

默认构造函数将自动调用(对于非POD类型)。如果你需要一个不同的构造函数,那就没办法了,但你可以使用vector代替,它将支持你所需的内容。


3

你不能这么做。

数组中的每个元素都将由默认构造函数(无参数构造函数)初始化。

最好的替代方法是使用向量。
在这里,您可以指定一个值,该值将被复制构造到向量的所有成员中:

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
}

1

首先,A类应该有一个默认构造函数,否则B()将无法编译。它会在构造函数开始执行之前尝试调用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接