How to initialize a large private array in a class using constructor(just a constructor) in c++? [duplicate]

随声附和 提交于 2020-01-16 12:02:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!