class 中类型 "char text [100]" 的探测器类型
Prober type for type "char text [100]" in class
我有以下内容,但我不知道我做错了什么。我显然在参数定义中有错误的类型,但我无法弄清楚正确的语法是什么。
dto.h
...
class Dto
{
public:
struct msg
{
int id;
byte type;
char text[100];
};
char* getText();
void setText(char* text);
private:
Dto::msg message;
...
dto.cpp
...
char* Dto::getText()
{
return Dto::message.text;
}
void Dto::setText(char* text)
{
Dto::message.text = text;
}
...
编译时得到:
Dto.cpp:85:30: error: incompatible types in assignment of 'char*' to 'char [100]' Dto::message.text = text;
不能给数组赋值。要将 C 字符串复制到 char
数组,您需要 strcpy
:
strcpy(Dto::message.text, text);
更好的是,使用 strncpy
来确保您不会溢出缓冲区:
strncpy(Dto::message.text, text, sizeof(Dto::message.text));
Dto::message.text[sizeof(Dto::message.text)-1] = 0;
请注意,如果源字符串太大,您需要在末尾手动添加一个空字节,因为在这种情况下 strncpy
不会以空终止。
我有以下内容,但我不知道我做错了什么。我显然在参数定义中有错误的类型,但我无法弄清楚正确的语法是什么。
dto.h
...
class Dto
{
public:
struct msg
{
int id;
byte type;
char text[100];
};
char* getText();
void setText(char* text);
private:
Dto::msg message;
...
dto.cpp
...
char* Dto::getText()
{
return Dto::message.text;
}
void Dto::setText(char* text)
{
Dto::message.text = text;
}
...
编译时得到:
Dto.cpp:85:30: error: incompatible types in assignment of 'char*' to 'char [100]' Dto::message.text = text;
不能给数组赋值。要将 C 字符串复制到 char
数组,您需要 strcpy
:
strcpy(Dto::message.text, text);
更好的是,使用 strncpy
来确保您不会溢出缓冲区:
strncpy(Dto::message.text, text, sizeof(Dto::message.text));
Dto::message.text[sizeof(Dto::message.text)-1] = 0;
请注意,如果源字符串太大,您需要在末尾手动添加一个空字节,因为在这种情况下 strncpy
不会以空终止。