2013-05-31 181 views
-1

我已經開始學習C++,並在處理多個文件時陷入困境。爲了實踐基本類,我寫了三個不同的文件,如何從多個C++文件構建二進制文件?

  • working.cpp
  • word.cpp
  • word.h

word.cpp:

#include <iostream> 
#include "word.h" 
using namespace std; 
class word{ 

public: 
char *word; 

void createWord(char *str) 
{ 
    word = str; 
} 

void print_word(void) 
{ 
    cout<<word<<endl; 
} 

char * getWord() 
{ 
    return word; 
} 

}

working.cpp

#include <iostream> 
#include "word.h" 
void printWord(word); 
using namespace std; 
int main() 
{ 
word one; 
one.createWord("one"); 

printWord(one); 

} 

void printWord(word a) 
{ 
cout<<a.getWord()<<endl; 
} 

word.h

class word; 

這是三個不同的文件,所以我不知道如何編譯它們。我曾嘗試爲
g++ working.cpp word.cpp

然而,編譯器無法識別的字爲一類,並給了我下面的錯誤

working.cpp: In function 'int main()': 
working.cpp:7:7: error: aggregate 'word one' has incomplete type and cannot be defined 
working.cpp:7:12: error: aggregate 'word two' has incomplete type and cannot be defined 
working.cpp:7:17: error: aggregate 'word three' has incomplete type and cannot be defined 
working.cpp: In function 'void printWord(word)': 
working.cpp:19:6: error: 'aha' has incomplete type 
In file included from working.cpp:2:0: 
word.h:2:7: error: forward declaration of 'class word' 
word.cpp:25:1: error: expected ';' after class definition 

我在做什麼錯在編譯時?

+2

從一本好書開始,代碼有很多問題。 – lekroif

回答

4
  1. 您需要在頭文件中包含更多word的定義。事情是這樣的:

    class word 
    { 
    public: 
        char *word; 
        void createWord(char *str); 
        void print_word(void); 
        char * getWord(); 
    }; 
    
  2. 然後,更改word.cpp只是有實現:

    void word::createWord(char *str) 
    { 
        word = str; 
    } 
    
    void word::print_word(void) 
    { 
        cout<<word<<endl; 
    } 
    
    char * word::getWord() 
    { 
        return word; 
    } 
    
  3. 編譯和鏈接!

你需要有更多的word類的頭,使您的其他翻譯單元可以知道類是多大(保留爲正在創建的實例有足夠的空間),以及知道您要調用的方法的名稱。

+0

謝謝,我試過了,它工作。我有點習慣於如何用更高級的語言定義類,因此在編寫類時讓我感到困惑。 – iamseiko

3

僅僅提到頭文件中的類名稱(所謂的正向聲明)是不夠的;你需要一個完整的類聲明(該聲明類的所有字段和功能):

class word { 
public: 
    char *word; 
    void createWord(char *str); 
    void print_word(void); 
    char * getWord(); 
}; 
3

word類的word.h

word.h:2:7: error: forward declaration of 'class word' 

沒有實際的聲明,我建議你讀了Bjarne Stroustrup出色的書籍「The C++ Programming Language」開始。

+0

謝謝,我會檢查出書。 – iamseiko