【发布时间】:2017-07-26 21:21:36
【问题描述】:
我能够生成一段可编译的代码,将结构传递给函数,但是当我尝试使用“按值传递”时,我的代码就崩溃了。
我已经研究了如何在多个文件中使用相同的格式化结构,但我不确定在按值传递函数时是否有任何不同?
注意:这是在 arduino IDE 中用 C++ 编写的
我的地址传递代码如下:
passingStructs.ino
#include "a.h"
#include "b.h"
myStruct volatile structure1;
void setup() {
}
void loop() {
structure1.foo = 7;
structure1.bar = 11;
int lower = minusData(&structure1);
int higher = addData(&structure1);
}
啊.h:
#include "b.h"
#ifndef __a_h
#define __a_h
//prototype functions
int addData(struct myStruct *structureC);
#endif //__a_h
a.cpp:
#include "a.h"
#include "b.h"
int addData(struct myStruct *structureC) {
int x = structureC->foo;
int y = structureC->bar;
return (x + y);
}
b.h:
#ifndef __b_h
#define __b_h
//Define structure
typedef struct myStruct {
int foo;
int bar;
};
//Prototype functions
int minusData(struct myStruct *structureC);
#endif //__b_h
b.cpp:
#include "b.h"
myStruct structureC;
int minusData(struct myStruct *structureC) {
int x = structureC->foo;
int y = structureC->bar;
return (x - y);
}
但是,如果我使用 int 更高 = addData(structure1); 在 .ino 文件中和
int addData(struct myStruct structureC) {
int x = structureC.foo;
int y = structureC.bar;
return (x + y);
}
在头文件中具有相同原型的a.cpp文件中,编译器拒绝代码说
no matching function for call to ‘myStruct::myStruct(volatile myStruct&)’
有什么想法吗?
【问题讨论】:
-
__a_h是为实现保留的标识符。通过定义它,你谴责你的程序有未定义的行为。 -
这个问题好像和C语言没有关系。
-
您的
a.h是否有addData的按值重载原型? -
错误消息表明编译器正在为
myStruct结构寻找构造函数,该结构引用myStruct类型对象。这段代码在使用typedef时有点乱码。看起来您正在尝试编写 C 源代码但使用 .cpp 文件,因此编译器将其视为 C++ 而不是 C。 -
@RichardChambers 我已将文件更改为 .c 而不是 .cpp。但是我仍然不确定如何使用 typedef 来减少你所说的“乱码”?