如何在另一个C 标头文件中导入类

How to import a class in another C++ header file?

本文关键字:文件 导入 另一个      更新时间:2023-10-16

我在构造课程时遇到了一个问题。类"图形"在另一个文件中导入类"袋",然后使用"袋子"作为其组件。

//Graph.h
#ifndef GRAPH_H
#define GRAPH_H
#include <fstream>
#include <iostream>
#include <vector>
#include "Bag.h"
class Bag;
class Graph
{
public:
    Graph(int V);
    Graph(std::ifstream& in_file);
    int getV() { return V; }
    int getE() { return E; }
    void addEdge(int v, int w);
    void showadj() ;
private:
    int V;
    int E;
    std::vector<Bag> adj;
};
#endif

和" bag.h"如下:

//Bag.h
#ifndef BAG_H
#define BAG_H
#include <vector>
#include <iostream>
class Bag
{
public: 
    Bag();
    void addBag(int i) { content.push_back(i); }
    void showBag();
private:
    std::vector<int> content;
};
#endif 

graph.cpp:

//Graph.cpp
#include "Graph.h"
#include "Bag.h"
Graph::Graph(int V) : V(V), E(0)
{
    for (int i = 0; i < V; i++)
    {
        Bag bag;
        adj.push_back(bag);
    }
}

bag.cpp(对不起,算了):

#include "Bag.h"
void Bag::showBag()
{
    for (int i : content)
    {
        std::cout << i << " ";
    }
}

当我尝试补充这两个类时,出现错误说:

C:UsersADMINI~1AppDataLocalTempccMj4Ybn.o:newtest.cpp:(.text+0x1a2): undef
ined reference to `Bag::Bag()'
collect2.exe: error: ld returned 1 exit status

您还需要实现构造函数Bag::Bag(),因为它在Bag.cpp文件中丢失。

这是错误告诉您的。如果您不需要构造函数,则应将其从类定义中删除,这也可以解决此错误。

另一种选择是在Bag.h文件中提供一个空构造函数

class Bag
{
public: 
    Bag() {}
...
}