在不同的.cpp文件中使用结构 [英] Using structure in a different .cpp files
本文介绍了在不同的.cpp文件中使用结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用不同文件中的结构和定义结构的函数.根据建议的此处,我正在执行以下操作:
I am trying to do use a structure and the function defining the structure in different files. As suggested here I am doing the following:
我定义我的 struct
并将其保存在文件 agent.h
I define my struct
and save it in the file agent.h
// File agent.h
#ifndef AGENT_H
#define AGENT_H
#include "stdafx.h"
#include <random>
#include <vector>
#include <iostream>
// Define Nodes and Agents
struct Agent
{
int home, work; // Locations
int status; // S=0; E=1; I=2; R=3
Agent *initialize_agents(int N, int V);
Agent()
{
status = 0;
}
}A;
#endif
我将函数定义为函数,并将其另存为 agent.cpp
I defined the function the function and saved it as agent.cpp
// File agent.cpp
#include "stdafx.h"
#include <random>
#include <vector>
#include <iostream>
#include "Agent.h"
using namespace std;
Agent *initialize_agents(int N, int V)
{
Agent *A = new Agent[N];
char fileN[1024] = "myFile.dat";
FILE *f = fopen(fileN, "r"); // Binary File Home Work
int k = 0;
int v = 0;
while (!feof(f))
{
int i, j;
fscanf(f, "%d %d", &i, &j);
A[k].home = i;
A[k].work = j;
k++;
}
return(A);
}
然后我有主文件 main.cpp
// File agent.cpp
#include "stdafx.h"
#include <vector>
#include <iostream>
#include "agent.h"
using namespace std;
int main()
{
int Inet;
struct Agent;
int V = 100;
int N = 100;
Agent *A = initialize_agents(N, V); // Initialize Agents
return 0;
}
我收到以下错误:
error: 'initialize_agents' was not declared in this scope
推荐答案
在这里,您的代码已固定进行编译-
Here's your code fixed to compile -
agent.h:
// File agent.h
#ifndef AGENT_H
#define AGENT_H
#include "stdafx.h"
#include <random>
#include <vector>
#include <iostream>
// Define Nodes and Agents
struct Agent
{
int home, work; // Locations
int status; // S=0; E=1; I=2; R=3
Agent()
{
status = 0;
}
};
Agent *initialize_agents(int N, int V);
#endif
agent.cpp:
agent.cpp:
// File agent.cpp
#include "stdafx.h"
#include <random>
#include <vector>
#include <iostream>
#include "Agent.h"
using namespace std;
Agent *initialize_agents(int N, int V)
{
Agent *A = new Agent[N];
char fileN[1024] = "myFile.dat";
FILE *f = fopen(fileN, "r"); // Binary File Home Work
int k = 0;
int v = 0;
while (!feof(f))
{
int i, j;
fscanf(f, "%d %d", &i, &j);
A[k].home = i;
A[k].work = j;
k++;
}
return(A);
}
main.cpp:
// File agent.cpp
#include "stdafx.h"
#include <vector>
#include <iostream>
#include "agent.h"
using namespace std;
int main()
{
int Inet;
int V = 100;
int N = 100;
Agent *A = initialize_agents(N, V); // Initialize Agents
return 0;
}
这篇关于在不同的.cpp文件中使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文