c++ - 在不同的 .cpp 文件中使用结构

标签 c++ struct include

我正在尝试在不同的文件中使用结构和定义结构的函数。按照建议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/

相关文章:

将结构从 src 复制到 dst

php - 如何在 Yii2 项目中添加 PHP 请求

c++ - 将包含 vector 和cv::Mat的结构存储到磁盘-C++中的数据序列化

linux - 不能在 Linux 上包含自由类型 header

c - 我是否必须包含包含函数定义的 C 文件?

c++ - 编译 SFML 2.0 项目时加载共享库时出错

c++ - 除以指针值和注释符号

c++ - 如何检查 C++ 类构造函数中的参数大小

c++ - 定义一个接受模板类参数的模板函数

c++ - 指针类 C++