首页 > 解决方案 > 在不同的 .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

标签: c++structinclude

解决方案


这是固定编译的代码-

代理.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;
}

推荐阅读