我正在尝试在不同的文件中使用结构和定义结构的函数。按照建议here我正在做以下事情:
我定义了我的 struct
并将其保存在文件 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
// 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
最佳答案
这是固定编译的代码 -
代理.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
代理.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);
}
主要.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;
}
关于c++ - 在不同的 .cpp 文件中使用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54649234/