如何访问另一个文件中的结构数组。假设我有 3 个文件 1.h 2.cpp 3.cpp,如下所示
1.h
#include<stdio.h>
struct st
{
Int i;
char ch[10];
};
struct st var[10];
2.cpp
#include"1.h"
int main
{
int s;
//here i hve scannd value of i frm user
callotherfile();
}
我 3.cpp
#include"1.h
int p;
void callotherfile(void)
{
for(p=1;p<=10;p++)
cout<<var.i[p]<<end;// is it good can i excess?
}
这里我遇到了错误,因为 p 和 s 不是类类型,请帮助我修复它
我正在编译为 g++ 2.cpp 3.cpp
最佳答案
我建议进行以下更改:
对
1.hpp
的更改.- 删除
#include <stdio.h>
.你不需要它。 为数组提供声明,而不是定义。
struct st { int i; // You had Int, not int. I assume that was a typo. char ch[10]; }; extern struct st var[10];
- 删除
对
2.cpp
的更改.为callotherfile
提供声明在使用之前。#include "1.h" void callotherfile(void); int main() { int s; // This is an unused variable. It can be removed. callotherfile(); // You had a : not a ;. I assume that was a typo }
对
3.cpp
的更改.- 添加
#include <iostream>
.您需要它才能使用std::cout
和std::endl
. - 提供数组的定义。
- 使用
cout
和endl
与std::
范围。 - 自
var
是一个数组,使用var[p].i
而不是var.i
. 当循环计数器达到
p
时停止循环,而不是当它超过p
时.请注意10
不是具有10
的数组的有效索引元素。#include <iostream> #include "1.h" struct st var[10]; int p; // This variable can be moved to the function scope. void callotherfile(void) { for(p=1;p<10;p++) // You had p<=10 std::cout<<var[p].i<<std::endl; }
- 添加
关于c++ - 如何访问另一个文件中的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601586/