我正在学习如何使用类保存多个值并从函数返回实例。另一种选择是使用全局变量,这可能更简单,但我想学习C++中的课程。
唯一给我带来麻烦的是从构造函数参数分配给string字段。我尝试过这段代码的几个变体,但都没有编译。
这是我目前遇到的错误:
构造函数'RelayInfo::RelayInfo(int,char*):17: error:在将'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 );
}
}发布于 2015-01-29 16:37:39
定义必须是:
RelayInfo( int pin, char* message );甚至更好:
RelayInfo( int pin, const char* message );编辑:
此外,您可能应该使用:
用于复制char指针的strncpy()。
发布于 2015-01-29 20:26:15
根据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 );
}
}https://stackoverflow.com/questions/28219715
复制相似问题