我一直在阅读大量有关将结构成员传递给函数的资料。但是,如果有人可以澄清我要去哪里错了,我将不胜感激。我预测这更多是编译顺序/定义错误,尽管也可能存在语法错误。
据我所知,我能够修改结构成员数据,并通过作为引用(在本例中不是指针)传递来避免任何复制。此方法还允许我保留用于访问函数内各个成员的点分符号。
主要.cpp:
// include headers
struct foo{
int a;
int b;
}foo_data;
int main(){
foo_data.a = 1; // assign some values to the member in standard format.
foo_data.b = 2;
function(foo_data);
// should this be &foo_data, am I passing by value here as it is
// or is the declaration taking care of that?
}
函数.h:
void function(foo &) // function declaration reference of type foo
函数.cpp:
void function(foo &foo_data) // function definition reference of type foo
{
foo_data.a; // should == 1
foo_data.b; // should == 2
}
错误通常与未声明的标识符有关,即 foo_data。我是否需要告诉 functions.h 中的声明我正在向它传递一个结构,或者实际上是一个 int(引用?)
谢谢!
最佳答案
根本原因:
您收到错误是因为编译器不知道/理解您在 cpp 文件中使用的类型 foo
。只有当它看到它的定义时它才能知道类型。
解决方案:
您需要将结构的声明放在头文件中,并将该头文件包含在声明函数的头文件和定义函数的 cpp 文件中。
函数.h
struct foo{
int a;
int b;
};
extern foo foo_data;
void function(foo &);
函数.cpp
#include "functions.h"
foo foo_data;
void function(foo &foo_data) function definition reference of type foo
{
//access local foo_data
foo_data.a // should = 1
foo_data.b // should = 2
//access global foo_data
::foo_data.a = 1;
::foo_data.b = 1;
}
main.cpp
#include "functions.h"
int main()
{
//Global foo_data is accessible here now
foo_data.a =
foo_data.a =
....
}
编辑:
你的评论表明你想在多个源文件中共享一个 foo_data
实例,在这种情况下你应该使用 extern
,我修改了上面的代码示例来这样做,注意里面function()
本地 foo_data
实例将隐藏全局实例,如果您想使用全局对象,则必须将其用作 ::foo_data
.
关于C++ 通过引用修改函数的结构值(可能是编译顺序问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955526/