库构造函数中的数组解析-指针问题(C ++)

时间:2019-03-27 10:40:04

标签: c++ arrays pointers constructor arduino

我正在尝试开发由两个类组成的Arduino库。我希望“ WayPointStack”存储“ WPCommand”的数组,但无法正常工作。

这显然是指针问题,但我不知道如何解决。我的代码中剩下四个错误:

WayPointStack.cpp:23:7: error: incompatible types in assignment of 'WPCommand*' to 'WPCommand [0]'
_wp = new WPCommand[arrSize]; //Fixed

WayPointStack.cpp:44:34: error: could not convert '(operator new(16u), (((WPCommand*)<anonymous>)->WPCommand::WPCommand(4, 10000), ((WPCommand*)<anonymous>)))' from 'WPCommand*' to 'WPCommand'
return new WPCommand(_END, 10000);

WayPointStack.cpp:59:15: error: no match for 'operator=' (operand types are 'WPCommand' and 'WPCommand*')
_wp[pointer] = new WPCommand(target, time); # Fixed

WPCommand.h:10:7: note: candidate: WPCommand& WPCommand::operator=(const WPCommand&)
class WPCommand # Does not appear anymore, fixed

WPCommand.h

#ifndef WPCommand_h
#define WPCommand_h

#include "Arduino.h"

class WPCommand
{
  public:
    WPCommand(int target, int time );
    WPCommand();
    int GetTarget();
    int GetTime();
    int LEFT;
    int RIGHT;
    int FORWARD;
    int BACKWARD;
    int STOP;
    int END;
  private:
    int _target;
    int _time;
};
#endif

WayPointStack.h

#ifndef WayPointStack_h
#define WayPointStack_h

#include "Arduino.h"
#include "WPCommand.h"

class WayPointStack
{
  public:
    WayPointStack();
    WayPointStack(WPCommand wp[], int length);
    WPCommand GetNextWP();
    WPCommand GetWP(int i);
    void AddWP(int target, int time);
    int SetWPPointer(int i);
    int GetWPPointer();
    int GetLength();
  private:
    WPCommand _wp[];
    int pointer;
    int _length;
};

#endif

WayPointStack.cpp(部分)

#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"
#define _BACKWARD 0
#define _FORWARD 1
#define _STOP 2
#define _LEFT 3
#define _RIGHT 4
#define _END 4
#define arrSize 100

WayPointStack::WayPointStack()
{
  _wp = new WPCommand[arrSize];
  _length = 0;
  pointer = 0;
}

WayPointStack::WayPointStack(WPCommand wp[], int length)
{
    _wp = new WPCommand[arrSize];
    for (int i = 0; i < length; i++){
        _wp[i] = wp[i];
    }
    _length = length;
    pointer = 0;
}

WPCommand WayPointStack::GetNextWP()
{
    if (pointer < _length){
        pointer++;
        return _wp[pointer-1];
    }
    return new WPCommand(_END, 10000);
}

我尝试或多或少地随机引用和取消引用_wp和wp [],但是它不起作用。

编辑: 更改

WPCommand _wp[];

WPCommand *_wp;

成功修复了第一个错误。对

做同样的事情
WayPointStack(WPCommand *wp, int length);

编辑:

_wp[pointer] = WPCommand(target, time);

代替

_wp[pointer] = new WPCommand(target, time);

成功修复了错误编号3。

编辑:

return WPCommand(_END, 10000);

固定的错误编号2。

问题解决了。

0 个答案:

没有答案