我环顾四周,只找到了一个解决方案,与另一个冲突。我有具有一些const成员和其他需要初始化的成员的A类具有一些构造函数和A的2D数组的类B]
像这样:
class A {
public:
A();
A(t, u);
const int x = 5;
private:
int _t;
int _u;
}
class B {
public:
B();
A a[50][500];
}
A::A() {
//nothing here
}
A::A(t, u) {
_t = t;
_u = u;
}
B::B() {
for (int i=0; i<50; i++)
for(int j=0; j<500; j++)
a[i][j] = A(i, j);
}
现在,这不起作用,因为A有一个const成员,所以赋值失败了,因为所有a都已经默认构造,我显然不想在B的成员初始值设定项列表中编写25000个初始值设定值没问题。
我需要默认的初始化程序,因为否则B的构造函数将抛出一个错误,即我无法默认初始化数组,因此我需要某种方式来用A的新构造对象重新分配该数组。我该怎么办?
这就是你想要的?
class A {
public:
A();
A(int t, int u);
const int x = 5;
A& operator=(const A& a);
private:
int _t;
int _u;
};
class B {
public:
B();
A a[50][500];
};
A::A() {
//nothing here
}
A& A::operator=(const A& a) {
_t = a._t;
_u = a._u;
}
A::A(int t, int u) {
_t = t;
_u = u;
}
B::B() {
for (int i=0; i<50; i++)
for(int j=0; j<500; j++)
a[i][j] = A(i, j);
}
您只是缺少=运算符
如果要避免默认初始化数组,可以使用std::vector<std::vector<A>>
并将其填充到B的构造函数中:
class A {
public:
A(t, u);
const int x = 5;
private:
int _t;
int _u;
}
class B {
public:
B();
std::vector<std::vector<A>> a;
}
A::A(t, u) {
_t = t;
_u = u;
}
B::B()
: a(50) { // a will contain 50 empty rows
for (int i=0; i<50; i++) {
a[i].reserve(500); // allocates enough space in each row for at least 500 elements
for(int j=0; j<500; j++)
a[i].emplace_back(i, j); // constructs value in-place using given arguments
}
}
请注意,您不再需要A的空参数构造函数,因此我将其删除。