C ++在Classes中使用Class对象

时间:2013-12-09 20:24:15

标签: c++ class

我在另一个类中使用类对象时遇到了困难。我在Arduino库中,并有以下简化代码

eh.h

#include <SoftwareSerial.h>

class EH_Serial_class : public Stream
{
private:
  uint8_t _mode;
  SoftwareSerial *_soft;  // SoftwareSerial is from SoftwareSerial.h

public:
  EH_Serial_class();
  ~EH_Serial_class();
  void config_soft(SoftwareSerial *soft);
}

eh.cpp

#include "eh.h"
EH_Serial_class::EH_Serial_class()
{
  _mode = 0;
  _soft = 0;
}

EH_Serial_class::~EH_Serial_class()
{
}

void EH_Serial_class::config_soft(SoftwareSerial *soft){
  _mode = EH_SOFT_SERIAL;
  _soft = soft;
}

我在SoftwareSerial的第一个声明中得到error: ‘SoftwareSerial’ has not been declared的错误

有人可以帮忙吗?

修改 在听完Jeffery的建议之后,我遇到了一个新的错误。

eh.h

//#include <SoftwareSerial.h>
class SoftwareSerial;

class EH_Serial_class : public Stream
{
private:
  uint8_t _mode;
  SoftwareSerial *_soft;  // SoftwareSerial is from SoftwareSerial.h

public:
  EH_Serial_class();
  ~EH_Serial_class();
  void config_soft(SoftwareSerial *soft);
  virtual size_t write(uint8_t byte);
}

eh.cpp

#include <SoftwareSerial.h> // tried after "#include eh.h" as well
#include "eh.h"

EH_Serial_class::EH_Serial_class()
{
  _mode = 0;
  _soft = 0;
}

EH_Serial_class::~EH_Serial_class()
{
}

void EH_Serial_class::config_soft(SoftwareSerial *soft){
  _mode = EH_SOFT_SERIAL;
  _soft = soft;
}

size_t EH_Serial_class::write(uint8_t byte){
  switch(_mode){
  case EH_STD_SERIAL:
    return Serial.write(byte);
  case EH_SOFT_SERIAL:
    return _soft->write(byte);
  default:
    return 0;
  }
  return 0;
}

我收到错误:

error: invalid use of incomplete type ‘struct SoftwareSerial’
error: forward declaration of ‘struct SoftwareSerial’

我想我正确使用指针......我现在做错了什么?

1 个答案:

答案 0 :(得分:1)

删除此行:

#include <SoftwareSerial.h>

并在开头添加这个:

class SoftwareSerial;

以上是一个不完整的类型声明,足以让编译器使用您的类指针(因为您没有对指针执行任何其他操作,除非指定它)。