解决了! (见编辑)
我正在尝试初始化几个数组,它们是某个类的私有(private)成员。我正在尝试使用公共(public)函数来初始化这些私有(private)数组。我的代码如下所示:
void AP_PitchController::initGains(void){
_fvelArray[] = {20, 25, 30, 60, 90, 130, 160, 190, 220, 250, 280};
_kpgArray[] = {6.0, 6.0, 8.0, 4.0, 3.0, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};
_kdgArray[] = {2000, 2000, 1900, 300, 300, 200, 200, 200, 200, 200, 200};
_kigArray[] = {0.1, 0.1, 0.2, 0.25, 0.3, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
这些数组可以在 header 文件 AP_PitchController 中找到,并在其中声明为私有(private)。当我尝试编译代码时,每次初始化都会收到以下消息之一:
/../AP_PitchController.cpp:106: error: expected primary-expression before ']' token /../AP_PitchController.cpp:106: error: expected primary-expression before '{' token /../AP_PitchController.cpp:106: error: expected `;' before '{' token
这是我的私有(private)声明:
Private:
uint8_t _fvelArray[];
float _kpgArray[];
float _kdgArray[];
float _kigArray[];
有谁知道我在调用 initGains() 时初始化这些数组做错了什么?
编辑:
我在其中一个相关问题中找到了答案。
我需要做的就是为初始化提供一个数组大小:
static float _kpgArray[11];
然后在 .cpp 文件中的函数之外对其进行初始化:
uint8_t AP_PitchController::_fvelArray[11] = {20, 25, 30, 60, 90, 130, 160, 190, 220, 250, 280};
感谢您的参与!
最佳答案
只能在声明时使用初始化语法:
float _array[2] = {0.1f, 0.2f};
声明后,您必须单独初始化成员:
_array[0] = 0.1f;
_array[1] = 0.2f;
或者你可以循环执行:
float temp[2] = {0.1f, 0.2f};
for( int i = 0; i < 2; ++i )
_array[i] = temp[i];
关于c++ - 初始化一个私有(private)数组c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21587883/