c++ - 结构定义错误,但前提是先前定义了函数
问题描述
这段简单的 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() {
}
编辑:声明struct
withtypedef
无济于事:
//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(){
^
解决方案
返回类型应该是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++ 参考页面。
推荐阅读
- c# - 按行号循环数据集
- html - 如何根据特定条件显示图像列表中的图像(使用 ColdFusion)
- svelte - page.params 在 SvelteKit 中未定义
- flutter - 运行 flutter pub upgrade 命令时出现握手错误
- sql-server - 尝试使用 sql_server_socket 将我的应用程序与 SQL Server 连接起来。在 SqlConnection.dart 中,未正确指定 guinness 包的版本
- azure-devops - Azure YAML Pipelines:如何在 Azure DevOps 的另一个项目中引用一个项目和 repo
- for-loop - FOR循环/向量化数列
- lua - 如何在 ROBLOX 中制作杀手机器人
- python - 在 Python 中录制时检测并分割静音
- mongodb - $ 查找 mongodb 对象数组