首页 > 解决方案 > 结构定义错误,但前提是先前定义了函数

问题描述

这段简单的 Arduino (C++) 代码失败并出现错误myType does not define a type
如果我注释掉doNothing函数,或者在定义struct.

这是怎么回事?


//it works if this is commented out
void doNothing() { }

struct myType {
  int x;
};

myType f(){ //error here: myType does not define a type
  myType m;
  m.x = 5;
  return m;
}

void setup() {
  myType p = f();
  int x = p.x;
}

void loop() {
}

编辑:声明structwithtypedef无济于事:


//it works if this is commented out
void doNothing() { }

typedef struct { //<-- using typedef
  int x;
} myType ;       // <-- type name at the end

myType f(){
  myType m;
  m.x = 5;
  return m;
}

void setup() {
  myType p = f();
  int x = p.x;
}

void loop() {
}

错误仍然是:

error: 'myType' does not name a type
 myType f(){
 ^

标签: c++arduino

解决方案


返回类型应该是struct myType 因为您没有将其声明为数据类型:

struct myType f(){ // this should work
    myType m;
    m.x = 5;
    return m;
}

如果要将其定义为编译器要考虑的类型,则需要使用 typedef 关键字将其定义为结构的别名:

typedef struct {
    int x;
} myType;

myType f(){ // Now myType does define a type
    myType m;
    m.x = 5;
    return m;
}

有关 typedef 的更多信息,请访问此 c++ 参考页面


推荐阅读