我有一个类,比方说,我想在构造函数中初始化Children参数:
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 = {}
说:”表达式必须有一个可修改的值”。”表达式必须有一个可修改的l值”。为什么会这样呢?
解决方案:
正如@L.F.和@UnholySheep所指出的那样,为了给类中的 Children
变量,它应该被添加到成员初始化器列表中,像这样。
Foo::Foo(const unsigned int index) : Index(index), Children(), Size(0.5/index) {}
这将会把Children变量初始化为一个全0的数组,然后可以在构造函数中进一步修改。
本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/180.html