简体   繁体   English

C ++:初始化静态成员大数组

[英]C++ : initialize static member large array

In order to use static data members in C++, I have currently something like that : 为了在C ++中使用静态数据成员,我目前有类似的东西:

// HEADER FILE .h
class MyClass {
private :
    static double myvariable;
};

// CPP FILE .cpp
double MyClass::myvariable = 0;

But if now I have : 但如果现在我有:

// HEADER FILE .h
class MyClass {
private :
    static double myarray[1000];
};

How can I initialize it ? 我该如何初始化它?

Thanks 谢谢

The same as you initialize ordinary arrays: 与初始化普通数组相同:

double MyClass::myarray[1000] = { 1.1, 2.2, 3.3 };

Missing elements will be set to zero. 缺失元素将设置为零。

Try this, 试试这个,

class MyClass {
private :
    static double myarray[1000];
};

double MyClass::myarray[]={11,22};

You could add a non-pod static member that would initialize myvariable from it's constructor 您可以添加一个非pod静态成员,该成员将从其构造函数初始化myvariable

This is a little like 'RIAA-by-proxy' if you will. 如果你愿意,这有点像'RIAA-by-proxy'。

Beware of the Static Initialization Fiasco 谨防静态初始化Fiasco

Why not do this - change the array to a vector. 为什么不这样做 - 将数组更改为向量。 Use another class that is a superclass of vector and do the initialisation of the array (vector) in its constructor. 使用另一个类是vector的超类,并在其构造函数中初始化数组(vector)。 You are then able to make it as complex as you require and also just treat it as an array> 然后,您可以根据需要将其设置为复杂,并将其视为数组>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM