2016-12-15 76 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() {} 
... 
} 
相關問題