【问题标题】:Expected ' ' in definition of struct结构定义中的预期“”
【发布时间】:2022-01-01 13:13:38
【问题描述】:

我现在正在做一个学校项目,我需要将两个结构定义为地址,如下面的代码所示:

typedef struct board_t* board;
/**
 * @brief Pointer to the structure that holds the game.
 */

typedef struct piece_t* piece;
/**
 * @brief Pointer to the structure that holds a piece
 */

如果我让它喜欢它,它就会编译。但是,一旦我尝试用括号替换分号来定义结构,就会出现编译错误。这是代码和错误:

typedef struct piece_t* piece{
/**
 * @brief Pointer to the structure that holds a piece
 */
 enum shape p_shape;
 enum size p_size;
 enum color p_color;
 enum top p_top;
 enum players author;
};


typedef struct board_t* board{
/**
 * @brief Pointer to the structure that holds the game.
 */
 piece array[4][4];
}

还有错误:

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
   53 | typedef struct board_t* board{

我需要做的是创建一个板子,里面装满了我可以在函数内部编辑的片段。 谁能帮帮我?

【问题讨论】:

  • 完全避免 typedef。使用 typedef 来掩盖类型是指针的事实是持续维护麻烦的秘诀。在某些情况下 typedef 很有用,但应谨慎使用。
  • @Exampleperson 您可以在不使用 typedef 的情况下制作不透明的结构。
  • IMO,typedef 唯一合理的地方是函数指针。
  • typedef 非常适合结构,因此您不需要将“struct”作为类型名的一部分,stackoverflow.com/questions/252780/… 我可能不会使用它们来隐藏新类型名的指针性质尽管。但归根结底,编译器设置规则,其他一切都只是一个指导方针,我们需要根据项目的需要使用我们的判断。
  • 我本来也想这样,但是老师让我们那样做,太糟糕了:(

标签: c struct definition


【解决方案1】:

我认为 typedef 名称需要放在最后

typedef struct piece_struct {
/**
 * @brief Pointer to the structure that holds a piece
 */
 enum shape p_shape;
 enum size p_size;
 enum color p_color;
 enum top p_top;
 enum players author;
}
piece;


typedef struct board_struct {
/**
 * @brief Pointer to the structure that holds the game.
 */
 piece array[4][4];
}
board;

如果您想要指针的 typedef 名称,则需要单独创建它们。

typedef piece* piece_ptr;
typedef board* board_ptr;

如果将结构定义与 typedef 分开,可能代码会更清晰:

struct piece_struct {
/**
 * @brief structure that holds a piece
 */
 enum shape p_shape;
 enum size p_size;
 enum color p_color;
 enum top p_top;
 enum players author;
};

typedef piece_str* piece;  // piece is a new name for a pointer
                           // to a piece_str

struct board_struct {
/**
 * @brief structure that holds the game.
 */
 piece array[4][4];
};

typedef struct board_struct* board;   // board is a new name for a pointer
                                      // to a board_str

我个人倾向于不为指针制作 typedef,因为我发现很难记住它是指针还是结构本身,所以我为结构制作了 typedef,并在声明指针时使用 *。

【讨论】:

  • 所以我需要创建一个结构,里面只有一个指针,指向一个带有实际板的结构?
  • typedef 只是为现有类型名创建一个新名称,所以 typedef piece* piece_ptr;不是在创建结构,它只是将 piece_ptr 作为与 piece* 相同的新类型名引入。将结构定义包装在 typedef 语句中是一种常见的习惯用法,但如果单独执行它们,代码可能更容易理解。
  • 哦,我明白了,谢谢你的回答,我希望它真的会帮助我
  • 没问题,希望项目顺利!
  • 您实际上可以在单个 typedef 语句中定义多种类型:typedef struct board { ... } board, *board_ptr; 但是为了便于阅读,应该避免使用它。在 typedef 后面隐藏指针也很容易混淆和出错。教新手这样的东西并不能帮助他们理解指针的概念。
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
相关资源
最近更新 更多