在 class 构造函数 c++ 中将其与指针数组一起使用
Using this with array of pointer in class constructor c++
我试图将一个指针数组分配给 nullptr。
class ToyBox
{
private:
Toy *toyBox[5];
int numberOfItems;
public:
ToyBox()
{
this->numberOfItems = 0;
this->toyBox = {}
}
}
在 this in this->toyBox:
处抛出错误
expression must be a modifiable lvalueC/C++(137)
有什么改正建议吗?
您只能以这种方式初始化数组:Assign a single value to array。但是在构造函数中你 could/must 使用成员初始化列表:
class ToyBox
{
private:
Toy *toyBox[5];
int numberOfItems;
public:
ToyBox() :
toyBox{nullptr}
, numberOfItems(0)
{
}
};
对于 C++,最好使用 std::array
而不是原始 C 数组:
相关:CppCoreGuidlines: ES.27
class ToyBox
{
private:
std::array<Toy*, 5> toyBox;
int numberOfItems;
public:
ToyBox() :
toyBox({nullptr})
, numberOfItems(0)
{
}
};
或者(我认为)更好:
ToyBox() : numberOfItems(0)
{
std::fill(toyBox.begin(), toyBox.end(), nullptr);
}
我试图将一个指针数组分配给 nullptr。
class ToyBox
{
private:
Toy *toyBox[5];
int numberOfItems;
public:
ToyBox()
{
this->numberOfItems = 0;
this->toyBox = {}
}
}
在 this in this->toyBox:
处抛出错误expression must be a modifiable lvalueC/C++(137)
有什么改正建议吗?
您只能以这种方式初始化数组:Assign a single value to array。但是在构造函数中你 could/must 使用成员初始化列表:
class ToyBox
{
private:
Toy *toyBox[5];
int numberOfItems;
public:
ToyBox() :
toyBox{nullptr}
, numberOfItems(0)
{
}
};
对于 C++,最好使用 std::array
而不是原始 C 数组:
相关:CppCoreGuidlines: ES.27
class ToyBox
{
private:
std::array<Toy*, 5> toyBox;
int numberOfItems;
public:
ToyBox() :
toyBox({nullptr})
, numberOfItems(0)
{
}
};
或者(我认为)更好:
ToyBox() : numberOfItems(0)
{
std::fill(toyBox.begin(), toyBox.end(), nullptr);
}