【问题标题】:Prober type for type "char text [100]" in class类中类型“char text [100]”的探测器类型
【发布时间】:2021-12-20 21:10:24
【问题描述】:

我有以下情况,但我不知道我做错了什么。我显然在参数定义中有错误的类型,但我不知道正确的语法是什么。

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;

【问题讨论】:

  • 你可能想使用strcpy(message.text, text);
  • 或使用std::strings
  • @TedLyngmo 不在 Arduino 上。
  • @gre_gor 我过去在 Arduino 上使用过它——但是自从我发现 Arduino STL 不做移动语义之后,我就停止了。它仍然比使用原始 char 数组 i.m.o 更安全/更容易。也许 Arduino String 是一个选择。

标签: c++ class arduino


【解决方案1】:

您不能分配给数组。要将 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 在这种情况下不会空终止。

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多