问题
Suppose we have a class like the following one:
class myprogram {
public:
myprogram ();
private:
double aa,bb,cc;};
myprogram::myprogram():aa(0.0),bb(0.0),cc(0.0){}
As you can see we can initialize our private members' aa, bb, cc using the myprogram() constructor.
Now, suppose I have a large private array G_[2000]. how I could initialize all the values of this array equal to 0 using a constructor.
class myprogram {
public:
myprogram ();
private:
double aa,bb,cc;
double G_[2000];};
myprogram::myprogram():aa(0.0),bb(0.0),cc(0.0){}
回答1:
You can write:
myprogram::myprogram()
{
for(int i=0;i<2000;i++)
G_[i]=0;
}
回答2:
Use std::memset function in constructor's body.
For example,
myprogram::myprogram()
: aa{0.0}, bb{0.0}, cc{0.0}
{
std::memset(G_, 0, 2000 * sizeof(double));
}
However, if you use braces {} in your initializer list, it will set default-initialize object (In case of array, it will fill it by zeroes).
来源:https://stackoverflow.com/questions/59729491/how-to-initialize-a-large-private-array-in-a-class-using-constructorjust-a-cons