2013-02-23 13 views
8

この再定義エラーを修正する方法は本当に分かりません。構造体エラーの再定義、私はそれを一度だけ定義しました

COMPILE + ERRORS

g++ main.cpp list.cpp line.cpp 
In file included from list.cpp:5:0: 
line.h:2:8: error: redefinition of âstruct Lineâ 
line.h:2:8: error: previous definition of âstruct Lineâ 

main.cppに

#include <iostream> 
using namespace std; 
#include "list.h" 

int main() { 
    int no; 
    // List list; 

    cout << "List Processor\n==============" << endl; 
    cout << "Enter number of items : "; 
    cin >> no; 

    // list.set(no); 
    // list.display(); 
} 

list.h

#include "line.h" 
#define MAX_LINES 10 
using namespace std; 

struct List{ 
    private: 
     struct Line line[MAX_LINES]; 
    public: 
     void set(int no); 
     void display() const; 
}; 

list.cpp

#include <iostream> 
#include <cstring> 
using namespace std; 
#include "list.h" 
#include "line.h" 

void List::set(int no) {} 

void List::display() const {} 

line.cpp

#include <iostream> 
#include <cstring> 
using namespace std; 
#include "line.h" 

bool Line::set(int n, const char* str) {} 

void Line::display() const {} 
+0

可能dupplicateで説明したように、警備員が含まれていますhttp://stackoverflow.com/questions/14792903/accessing-classes-from-another-source-in-c-issues-initializing- the-constructo/14792927#14792927 –

+0

ヘッダーガードを追加します。 –

答えて

10

list.cppには、 "line.h"と "list.h"の両方が含まれています。しかし、 "list.h"にはすでに "line.h"が含まれているので、実際には "list.h"がコードに2回含まれています。 (プリプロセッサは、既に持っているものを含まないほどスマートではありません)。

2つの解決策があります。

  • があなたのlist.cppファイルに直接「list.h」が挙げられるが、それはスケールしない練習ではいけない:あなたのヘッダーの何ごとに覚えておく必要がありファイルが含まれており、非常に迅速に処理されます。
  • 使用@juanchopanza
+0

それはそれだった! 'list.h'に' line.h'が既に含まれているので、list.cppから 'line.h'を削除しました。ありがとう。 – eveo

20

#define MAX_CHARS 10 
struct Line { 
    private: 
     int num; 
     char numOfItem[MAX_CHARS + 1]; // the one is null byte 
    public: 
     bool set(int n, const char* str); 
     void display() const; 
}; 

line.hあなたのヘッダーにinclude guardsを配置する必要があります。

#ifndef LIST_H_ 
#define LIST_H_ 

// List.h code 

#endif 
+0

+1。そして毎回それをすることを決して忘れるべきではありません) – SChepurin

+0

これはCPPコースの紹介です。誰もこのようなコードを使用している人はいません。クラスでこれをカバーしていないので、私はできません。申し訳ありませんが、再定義のための別の簡単な解決策が必要です。 – eveo

+0

実際には、私の 'list.cpp'に' #include line.h'を削除するだけでした。とにかく、ありがとう! – eveo

1

"line.h"は2回含まれており、ヘッダーファイルにはガードが含まれていません。

あなたのようなものを追加した場合:あなたのヘッダファイルに

#ifndef LINE_H 
#define LINE_H 
... rest of header file goes here ... 
#endif 

を、それがすべての罰金を動作します。

関連する問題