c++ - 在不同的 .cpp 文件中使用结构
问题描述
我正在尝试使用结构和在不同文件中定义结构的函数。正如这里所建议的,我正在执行以下操作:
我定义我的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;
}
推荐阅读
- javascript - 如何在 tsconfig.json 设置之外编译根级 .ts 文件?
- android - 如何在 Android 11 中使用 Firebase 云消息传递的通知中设置自定义声音?
- firebase - 是否可以限制用户可以登录 Firebase 应用的设备数量?
- javascript - 使用javascript从svg中删除宽度和高度
- python - 如何在数据类 asdict() 输出中包含 ClassVars?
- java - Java Swing - 赋值(很快到期)继承和预览问题
- java - 通过 AWS Java SDK 从 S3 读取文本文件时出错
- sql - 如何使用 postgresql 按多列中表示的值进行聚合
- python - TypeError: violinplot() 得到了一个意外的关键字参数“分位数”
- python - 如何导入我的日志记录设置而不是将其硬编码到脚本中?