如何为Arduino的C ++类中的构造函数分配字符串字段?

时间:2015-01-29 16:29:05

标签: c++ string arduino

我试图学习如何使用类来保存多个值并从函数返回一个实例。另一个选择是使用全局变量,这可能更简单,但我想学习C ++中的类。

唯一给我带来麻烦的是从构造函数参数中分配字符串字段。我已尝试过此代码的几种变体,但都没有编译。

这是我目前得到的错误:

在构造函数' RelayInfo :: RelayInfo(int,char *)': 17:错误:分配' char *'的不兼容类型到' char [20]'

自从我处理过C中的指针以来已经很长时间了。

//The RelayInfo class only has public fields and a constructor. 
//Its only purpose is to hold these values.
class RelayInfo
{
  public:
    RelayInfo(int pin, char message[20]);
    int Pin;
    char Message[20];
};

RelayInfo::RelayInfo( int pin, char message[20] )
{
  Pin = pin;
  Message = message*;
}

void setup() {  
  pinMode(13, OUTPUT);
  digitalWrite( 13, LOW );
}

void loop() {

  //Construct an instance of the class:
  RelayInfo info( 13, "Hello, World!" );

  //Use the fields from the class.
  if( info.Message == "Hello, World!" )
  {
    digitalWrite( info.Pin, HIGH );
  }  
}

2 个答案:

答案 0 :(得分:1)

定义必须是:

RelayInfo( int pin, char* message );

甚至更好:

RelayInfo( int pin, const char* message );

编辑:

此外,您应该使用:

strncpy()用于复制char指针。

答案 1 :(得分:0)

根据PDizzle745的建议,我想出了以下内容:

class RelayInfo
{
  public:
    RelayInfo(int pin, const char* message);
    ~RelayInfo();
    int Pin;
    char* Message;
};

RelayInfo::RelayInfo( int pin, const char* message )
{
  Pin = pin;

  //Allocate enough memory for copying the input string.
  Message = (char*) malloc( strlen(message) * sizeof(char) + 1 );

  //Copy the input string to the class's field.
  strcpy( Message, message );
}

RelayInfo::~RelayInfo(void)
{
  free( Message );
}

void setup() {
  pinMode(13, OUTPUT);

  digitalWrite( 13, HIGH );
  delay(1000);
}

void loop() {

  RelayInfo info( 13, "Hello" );

  if( strcmp( info.Message, "Hello" ) == 0 )
  {
    digitalWrite( info.Pin, LOW );
  }
}
相关问题