简体   繁体   中英

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?

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


}

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