c++ - 从库中获取函数的问题和奇怪的转换错误

标签 c++ constructor arduino static-libraries

我正在尝试编写一个 arduino 库。我之前写过一些类(class),但没有为 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);
}

移动性.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

移动.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;
}

错误

我在尝试修复代码时遇到了两个大错误。第一个是: 错误:请求从“Mobility*”转换为非标量类型“Mobility” 流动性 mol = new Mobility();

最佳答案

问题是由这一行引起的:

 Mobility mol = new Mobility();

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

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

所以你可以这样做:

Mobility mol;// static allocation

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

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

关于c++ - 从库中获取函数的问题和奇怪的转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180402/

相关文章:

C++ - 如何反复重新初始化对象?

c++ - 多重继承的模糊解决方法?

c++ - 当通过 New 调用时,Constructor 中的 Malloc 返回 NULL

c++ - 使用文字为模板类型赋值

arduino - 使用 Arduino 上 LED 的红外发射器发送 IR 值

c++ - 模拟需要直接使用参数的函数的更好方法

c++ - 构造函数导致 "use of deleted function"错误

c++ - 数组 + union + 包含位字段 C++ 的结构

c - Arduino myFile.write(buff, len) 不起作用

c++ - 如何找到 CL_DEVICE_MAX_WORK_GROUP_SIZE 的值