【发布时间】:2020-04-19 10:39:46
【问题描述】:
我有一堂课,比如说:
class Foo
{
public:
unsigned int Index;
float Size;
Foo(const unsigned int index);
~Foo();
private:
int Children[2][2];
};
而我想在构造函数中初始化Children参数:
Foo::Foo(const unsigned int index) : Index(index)
{
this->Size = 0.5 / index;
this->Children = {};
if (index < MAX_DIVS) {
for (int _x = 0; _x < 2; _x++) {
for (int _y = 0; _y < 2; _y++) {
this->Children[_x][_y] = 0;
}
}
}
我可以将初始值分配给Size做this->Size= 0.5/Index,但我无法初始化Children;
Visual Studio 在this->Children = {} 上给我一个错误说:“表达式必须有一个可修改的左值”。为什么会这样?
【问题讨论】:
-
你想用
this->Children = {};做什么?这似乎没有必要,因为无论如何你都会覆盖这些值? -
@UnholySheep 我正在尝试初始化它,因为 VIsual Studio 告诉我运算符 Foo::Foo 没有初始化 Foo::Children
-
先修正缩进。不能赋值给数组,也不能遍历三个索引的二维数组。
-
如果你想初始化一个数组,你应该在类声明中有一个默认值或者使用成员初始化列表(就像你已经为
Index所做的那样。事实上你的整个构造函数可以被简化至:Foo::Foo(const unsigned int index) : Index(index), Children(), Size(0.5/index) {} -
@Fabrizio 数组具有固定大小,因此值初始化数组值初始化其所有元素,从而产生一个全零数组。
标签: c++