从库中获取函数和奇怪的转换错误

时间:2016-03-23 14:03:28

标签: c++ constructor arduino static-libraries

我正在尝试编写一个arduino库。我以前写了几堂课,但没有为arduino写过什么。我一直遇到一个错误。首先让我告诉你代码:

代码

Main.ino(arduino项目)

#include <Wire.h>
#include "Mobility.h"

Mobility mol = new Mobility();
void setup() {
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
  Serial.println("loop");
  mol.move(true, 125, false, 125, 10);
  delay(2000);
}

Mobility.h

#ifndef MOBILITY_H
#define MOBILITY_H

#if (ARDUINO >= 100)
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif


const int DEFAULT_MOBILITY_ADD  = 4;

class Mobility
{
public:
    void begin();
    void begin(int address);
    int i2cAdd;
    int move(bool lPos, unsigned char leftPower, bool rPos, unsigned char rightPower, unsigned char msec);
private:

};
/**/
#endif

Mobility.cpp

#if (ARDUINO >= 100)
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif
#include "Mobility.h"
#include "Wire.h"


void Mobility::begin(){
    Wire.begin();
    this.i2cAdd = DEFAULT_MOBILITY_ADD;
}

void Mobility::begin(int address){
    Wire.begin();
    this.i2cAdd = address;
}

int Mobility::move(bool lPos, unsigned char leftPower,bool rPos, unsigned char rightPower, unsigned char msec){
  if (leftPower < -255 || leftPower > 255){
    return -1;
  }
  if (rightPower < -255 || rightPower > 255){
    return -2;
  }
  if(msec <= 0){
    return -3;
  }

  Wire.beginTransmission(this.i2cAdd);
  Wire.write(lPos);
  Wire.write(leftPower);
  Wire.write(rPos);
  Wire.write(rightPower);
  Wire.write(msec);
  Wire.endTransmission();
  return 0;
}

错误

在我尝试修复代码时,我遇到了两个重大错误。首先是:     错误:从&#39; Mobility *&#39;转换到非标量类型&#39; Mobility&#39;要求      流动性mol =新流动性();

1 个答案:

答案 0 :(得分:1)

问题是由这一行引起的:

 Mobility mol = new Mobility();

第一部分是静态内存分配:Mobility mol - 静态为对象mol分配内存。

第二部分使用动态内存分配:new - 动态分配内存。

所以你可以这样做:

Mobility mol;// static allocation

Mobility *mol = new Mobility(); //dynamic allcocation

但不是两者的混合。无论哪种方式,在创建对象时都会调用构造函数。