2016-12-15 78 views
0

构建课程时遇到问题。类“Graph”在另一个文件中导入一个类“Bag”,并使用“Bag”作为其组件。如何在另一个C++头文件中导入一个类?

//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:\Users\ADMINI~1\AppData\Local\Temp\ccMj4Ybn.o:newtest.cpp:(.text+0x1a2): undef 
ined reference to `Bag::Bag()' 
collect2.exe: error: ld returned 1 exit status 
+2

你需要建立'Bag.cpp'成'Bag.o'与'Graph.o' – StoryTeller

+1

袋联系起来。 cpp好奇地从这个问题中遗漏。 –

+0

如果您从'Graph.h'中删除'class Bag;'并从'Graph.cpp'中删除'#include“Bag.h”',它会起作用(因为'Graph.h'已经包含'Bag.h' )? – Aemyl

回答

4

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

这是错误告诉你的。如果你不需要构造函数,那么你应该从类定义中移除它,这也会解决这个错误。

另一种方法是提供一个空的构造在Bag.h文件

class Bag 
{ 
public: 
    Bag() {} 
... 
} 
相关问题