0

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?

Dave L
  • 3
  • 3
  • Note official C++ doesn't allow non-constant array size in any context at all except `new Type[count]`. Some compilers will sometimes allow it in certain other contexts as a language extension, but there are limits to how much supporting it in general is even possible. – aschepler Apr 29 '20 at 00:25

1 Answers1

3

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();


}
asmmo
  • 6,922
  • 1
  • 11
  • 25
  • 3
    And then if you want/know that `ANGULAR_RESO` will always be the size of the vector `sine`, eliminate the `ANGULAR_RESO` member and just use `sine.size()` instead, to avoid redundant data, extra code to keep them matched up, and bugs if they ever get out of sync. You can add an inline member function if it's still helpful to see that the size is called `ANGULAR_RESO` or similar. – aschepler Apr 29 '20 at 00:17