非类型错误和指针问题

时间:2016-04-23 07:54:22

标签: c++ class arduino eeprom

我目前收到以下消息:

从Arduino IDE收到错误: 请求'eType'中的成员'EEPROMWriteAny',它是非类型'EEPROMAnyType()'

我不认为我在代码中通过引用正确传递变量,因为这似乎是导致上面写错误的主要问题。 或者在类的类中有EEPROMWriteAny和EEPROM ReadAny导致此错误的原因是什么?我是否必须从EEPROMAnyType类指向然后指向U类?即使在嵌套类中也是EEPROMReadAny吗?

我使用EEPROM库提供了头文件,cpp源文件,arduino示例代码以及我如何定义下面类的关键字。 我还提供了一个图片,说明我的库在其文件夹中的样子,以防它出现问题。

标题文件:

#ifndef EEPROMAnyType_h
#define EEPROMAnyType_h

#include <Arduino.h>
#include <EEPROM.h>

class EEPROMAnyType
{
    public:
        template <class U> int EEPROMReadAny(unsigned int addr, U& x); //Reads any type of variable EEPROM
        template <class U> int EEPROMWriteAny(unsigned int addr, U& x);//Writes any type of variable to EEPROM
    private:
        int i;
        const byte *p[];
        byte *p[];
};

#endif

CPP文件:

#include "Arduino.h"
#include "EEPROM.h"
#include "EEPROMAnyType.h"

template <class U>  int EEPROMAnyType::EEPROMReadAny(unsigned int addr, U x)
{
  int i;
  byte* p[sizeof(x)] = (byte*)(void*) x; //(void*) makes variable x "typeless" and then (byte*) casts the typeless variable as a byte type
  for(i = 0; i < sizeof(x); i++){ // Why can I not declare i as an integer in the for loop?
    p[i]= EEPROM.read(addr+i);
  }
  return i;
}
template <class U>  int EEPROMAnyType::EEPROMWriteAny(unsigned int addr, U x)
{
  int i = 0;
  const byte* p[i] = (const byte*)(const void*) x;
  for(i = 0; i < sizeof(x); i++){
    EEPROM.write(addr+i, p[i]);
  }
  return i;
}

Arduino代码:

#include  <Arduino.h>
#include  <EEPROM.h>
#include  <EEPROMAnyType.h>


EEPROMAnyType eType(); // used to call EEPROMAnyType which can write/read any kind of data type to/from EERPOM
int addr = 10; //memory location to be pass by value to EEPROMAnyType functions
String *p;// To pass by reference to EEPROMAnyType functions
String x; //will be assigned to EEPROM location

void setup() {
  x = "memory";
  p = &x;
  Serial.begin(9600);
  Serial.println("Hello World");  //shows start point of code
  eType.EEPROMWriteAny(addr, *p);  //Writes to EEPROM memory 10
  x = eType.EEPROMReadAny(addr, *p); //assigns bytes from EEPROM memory location to x
}

void loop() {
  Serial.print("x: ");
  Serial.println(x);
  Serial.print("no. of bytes stored in x: ");
  Serial.println(EEPROMWriteAny(addr, p));
  delay(1000);
}

以下是我为EPPROMAnyType类定义关键字的方法:

EEPROMAnyType   KEYWORD1
EEPROMReadAny   KEYWORD2
EEPROMWriteAny  KEYWORD2

enter image description here

1 个答案:

答案 0 :(得分:0)

EEPROMAnyType eType(); - 编译器会将此语句解释为函数声明,其名称为eType,并且它的返回类型为EEPROMAnyType。因此,eType不是EEPROMAnyType的实例,并且在类的实例意义上使用eType会产生错误。希望这会有所帮助。