[英]How to access a structure array from 2 different files?
How would I go about doing something like this?我将如何 go 做这样的事情?
header.h header.h
struct myStruct;
extern myStruct array[];
main.cpp主文件
#include "header.h"
struct myStruct{
int a = 0;
};
myStruct array[5];
array[0].a = 1;
file2.cpp文件2.cpp
#include "header.h"
std::cout << array[0].a;
The size and layout of myStruct
needs to be known everythere you try to access its contents, so you must either define it inside of the.h file, or only access it using opaque pointers and dedicated functions.每次尝试访问其内容时都需要知道
myStruct
的大小和布局,因此您必须在 .h 文件中定义它,或者仅使用不透明指针和专用函数访问它。
Also, using C arrays in C++ is somewhat outdated.此外,在 C++ 中使用 C arrays 有点过时了。 You should use STL containers instead, such as
std::array<T, N>
or std::vector<T>
.您应该改用 STL 容器,例如
std::array<T, N>
或std::vector<T>
。
Well, first of all you should put struct
declarations in the header files.好吧,首先你应该把
struct
声明放在 header 文件中。
Second, you can't put assignments to arrays or std::cout
statements just loose in files.其次,您不能将分配给 arrays 或
std::cout
语句只是松散在文件中。 I'm assuming you did this for short code and not because you didn't know it needed to be in a function, but I'm pointing it out just in case.我假设你这样做是为了短代码,而不是因为你不知道它需要在 function 中,但我指出它以防万一。
Third, struct declarations require a semicolon三、struct声明需要分号
What you would do is have a header file:你要做的是有一个 header 文件:
header.hpp: header.hpp:
#pragma once
struct MyStruct {
int a = 0;
};
extern MyStruct array[5];
The extern
here means that the data is somewhere else.这里的
extern
表示数据在其他地方。 So let's make the somewhere else.所以让我们在别的地方做。
header.cpp: header.cpp:
#include "header.hpp"
MyStruct array[5];
main.cpp:主.cpp:
#include "header.hpp"
void someFunction() {
...
array[0].a = 1;
...
}
file2.cpp:文件 2.cpp:
#include <iostream>
#include "header.hpp"
void someOtherFunction() {
...
std::cout << array[0].a;
...
}
How would I go about doing something like this?
我将如何 go 做这样的事情?
You could go about doing something like what you did by doing something like what you did, except fixing the bugs in your attempt.您可以 go 通过做您所做的事情来做您所做的事情,除了修复您尝试中的错误。 Here is the list of bugs:
以下是错误列表:
myStruct
with a semicolon.myStruct
的定义。.c
suffix is conventionally for C source files while you're writing C++. .c
后缀通常用于 C 源文件,而您正在编写 C++。 Your compiler will likely be confused unless you provide some unconventional options to the compiler.cout
which you forgot to declare.cout
。 Or did you intend to use std::cout
?std::cout
? In that case you must include <iostream>
in order to use it, and use the appropriate namespace.<iostream>
才能使用它,并使用适当的命名空间。file2.c
, you use the class myStruct
in a way that depends on the definition of myStruct
without providing that definition.file2.c
中,您使用 class myStruct
的方式取决于myStruct
的定义而不提供该定义。array[0].a = 1;
and cout << array[0].a;
cout << array[0].a;
are expression statements.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.