Dave L
Dave L

Reputation: 3

Can I use non-constant array size for class members?

in the code below, uint16_t sine[ANGULAR_RESO] throws an error non static member reference must be relative to specific object struct

class BLDCControl  {
    public:
        uint16_t ANGULAR_RESO;
        uint16_t sine[ANGULAR_RESO];
        uint16_t pwm_resolution = 16;

}

What am I doing wrong?

Upvotes: 0

Views: 64

Answers (1)

asmmo
asmmo

Reputation: 7100

To use the class as it is written ANGULAR_RESO must be a compile time constant and in this way it is no longer a specific member for every object. It must be static. If you need a varying array size, use std::vector , as follows

class BLDCControl  {
    public:

        uint16_t ANGULAR_RESO;
        std::vector<uint16_t> sine;
        uint16_t pwm_resolution = 16;

}

And if ANGULAR_RESO is the size of your array (as @ aschepler suggested ), you can go without it because your std::vector has this size as a private member and you can get its value by std::vector<unit16_t>::size() method

#include <cstdint>
#include <vector>
struct BLDCControl  {
    BLDCControl(uint16_t ANGULAR_RESO, uint16_t pwm_resolution_v = 16) :
            pwm_resolution {pwm_resolution_v},
            sine {std::vector<uint16_t>(ANGULAR_RESO)}{}

    std::vector<uint16_t> sine;
    uint16_t pwm_resolution;

};
int main(){

    BLDCControl u(4, 16);
    std::cout << "ANGULAR_RESO is:\t"  << u.sine.size();


}

Upvotes: 3

Related Questions