CPP中的“无法访问”指针

时间:2018-04-08 07:11:21

标签: c++ pointers function-pointers

大家早上好。

我想调用我自己的函数,由父元素包含,它将值插入表中。

当我自己调用该函数时,插值有效。但是,当我调用相同的函数,通过父类的get方法传递时,程序终止,错误代码为-1。

这是我的函数标题:

class TabulatedFunction  : public AbstractUnivariateFunction , public AbstractClass {
public:
   TabulatedFunction();
   TabulatedFunction(float ** table, InterpolatorMode mode);
   virtual ~TabulatedFunction();
   float calculate(float* x);
   void setTabulatedValues(float ** table);
   float** getTabulatedValues();
   InterpolatorMode getMode();
   void setMode(InterpolatorMode mode);

private:
   float** tabulatedValues;
   InterpolatorMode mode;
};

这里的实现

float TabulatedFunction::calculate(float* xx){
float y=0.;
float x = xx[0];

// Interpolate threw the table
switch (mode) {
case InterpolatorMode::LINEAR:
{
    double diffByLow = 10000000.;
    double diffByUp = -1000000.;
    int iByLow = -1;
    int iByUp = -1;

    for(int i=0;i<sizeof(tabulatedValues[0][0]) ; i++ ){
        float diff = tabulatedValues[i][0] - x;
        if(fabs(diff) < diffByLow && diff < 0){
            diffByLow = fabs(diff);
            iByLow = i;
        }
        if(fabs(diff) < diffByUp && diff > 0){
            iByUp = i;
            diffByUp = fabs(diff);
        }
    }

    if(iByUp == -1){
        iByLow = sizeof(tabulatedValues[0][0])-2;
        iByUp = sizeof(tabulatedValues[0][0])-1;
    }
    else if(iByLow == -1){
        iByLow = 0;
        iByUp = 1;
    }
    cout << iByLow << endl;
    y = tabulatedValues[iByLow][1] +(x - tabulatedValues[iByLow][0]) *(tabulatedValues[iByUp][1] - tabulatedValues[iByLow][1])/((tabulatedValues[iByUp][0] - tabulatedValues[iByLow][0]));

}break;
case InterpolatorMode::TRIGONOMETRIC:
{
    y=0.;
}break;

default:{
    y=0.;
}break;
}

return y;
}

然后,将函数声明到我父母:

class TabulatedDynamicsModel : public AbstractDynamicsModel {
public:
   TabulatedDynamicsModel();
   virtual ~TabulatedDynamicsModel();



   void setThrustVsSpeedFunction(TabulatedFunction* thrustVsSpeedFunction);
   TabulatedFunction* getThrustVsSpeedFunction();

   TabulatedFunction* getAttitudeFunction();
   void setAttitudeFunction(TabulatedFunction* attitude);

private:
   TabulatedFunction thrustVsSpeedFunction;
   TabulatedFunction attitude;

};

感谢。

1 个答案:

答案 0 :(得分:2)

我认为你的问题是这一行

for(int i=0;i<sizeof(tabulatedValues[0][0]) ; i++ ){

tabulatedValues定义为float**,而sizeof上应用的tabulatedValues[0][0]并未提供数组第二维元素的数量。

在我的电脑上(gcc 64位),它返回:

sizeof(tabulatedValues) = sizeof(float **) = 8

sizeof(tabulatedValues[0]) = sizeof(float *) = 8

sizeof(tabulatedValues[0][0]) = sizeof(float) = 4

如果您将tabulatedValues定义为float tabulatedValues[rows][cols],则可以使用以下方法计算第二维(cols)的元素数量:

for(int i=0;i<sizeof(tabulatedValues[0] / tabulatedValues[0][0]) ; i++ ){

或只是

for(int i=0;i<boost::size(tabulatedValues[0]) ; i++ ){ // or std::size() on C++17

但是就像你使用指针一样,你应该提供大小(每行的cols数)作为函数的参数。