简体   繁体   中英

const int, member array size

My code basically:

class myclass : public singleton<myclass> {
    public:
        myclass();
    private:
        const float myfloat = 6000.0f;
        const int sz_arr = (int)myfloat;

        int arr[sz_arr];  // compiler complains about this line
};

Need to create arr at compile-time. Size of arr is known at compile-time! Ought to be computed based on myfloat value. How to achieve it? Also, myclass is singleton, only one instance of it is ever going to be created.

Firstly, sz_arr can't be used to specify the size of the array, you need to make it static . And mark myfloat as constexpr to make it known at compile-time (and better for sz_arr too).

class myclass : public singleton<myclass> {
    public:
        myclass();
    private:
        constexpr static float myfloat = 6000.0f;
        constexpr static int sz_arr = myfloat; // implicit conversion is enough

        int arr[sz_arr]; 
};

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