简体   繁体   中英

C++ : initialize static member large array

In order to use static data members in C++, I have currently something like that :

// 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

This is a little like 'RIAA-by-proxy' if you will.

Beware of the Static Initialization 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. You are then able to make it as complex as you require and also just treat it as an array>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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