2014-04-12 104 views
0

我在StackExchange上的第一篇文章! 我有一份C++課程的作業;使用以前分配的日期類(月,日,年)和時間類(小時,分鐘,上午/下午)的預約課程。 我認爲我有大部分的主要/語法錯誤。多重定義編譯錯誤

我的問題是,對於我目前如何完成#includes和頭文件,我得到一個多重定義錯誤的日期和時間的構造函數。(我不知道很多關於模板,但我需要與他們一起工作)

我的文件:

  • Appointment.cpp

    #include "time.cpp" 
    #include "date.cpp" 
    #include "appointment.h" 
    

    我需要能夠創建時間/日期對象,我應該使用.h或.cpp文件嗎?

  • Appointment.h

    #ifndef _APPOINTMENT_H_ 
    #define _APPOINTMENT_H_ 
    #include <iostream> 
    #include "time.h" 
    #include "date.h" 
    
  • date.cpp

    #ifndef _DATE_CPP_ 
    #define _DATE_CPP_ 
    #include "date.h" 
    
  • date.h

    #ifndef _DATE_H_ 
    #define _DATE_H_ 
    
  • time.cpp

    #ifndef _TIME_CPP_ 
    #define _TIME_CPP_ 
    #include "time.h" 
    
  • time.h中

    #ifndef _TIME_H_ 
    #define _TIME_H_ 
    

以下是有關執行上述文件:

  • 的main.cpp

    #include "arrayListType.h" 
    #include "appointment.h" 
    
    void read(arrayListType<Appointment>&); 
    void output(const arrayListType<Appointment>&); 
    
    int main() 
    { 
        arrayListType<Appointment> appointments; 
        read(appointments); 
        output(appointments); 
        return 0; 
    } 
    
  • read.cpp

    #include "arrayListType.h" 
    #include "appointment.h" 
    #include <fstream> 
    using namespace std; 
    
    void read(arrayListType<Appointment>& appointments) 
    {...} 
    
  • output.cpp

    #include "arrayListType.h" 
    #include "appointment.h" 
    #include <iostream> 
    #include <iomanip> 
    using namespace std; 
    
    void output(const arrayListType<Appointment>& appointments) 
    {...} 
    
  • arrayListType.h(其中有全部的實施,作爲模板)

  • itemType.h

不知道,如果你需要查看最後的2.如果我需要發佈更多信息,我很高興。我也有所有文件的壓縮版本。

+0

您正在使用[保留標識符](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)。 – chris

+4

只包含頭文件不是源單位 – johnbakers

+0

我沒有看到每個頭文件分別關閉'#endif'。他們在場嗎? –

回答

1

從Appointment.cpp刪除這些行:

#include "time.cpp" 
#include "date.cpp" 

你應該幾乎從來不包括從另一個的.cpp文件。因此,您還可以刪除您在.cpp文件中包含的包含警衛,因爲您不會包含它們。

main.cpp這些行必須在從main.cpp.cpp文件實現的功能包括一個頭文件:

void read(arrayListType<Appointment>&); 
void output(const arrayListType<Appointment>&); 

你似乎缺少的頭文件的地步。這個想法是分開接口實施。頭文件提供了不同單元需要知道的所有內容,以便能夠調用頭中列出的功能。一旦函數被調用,.cpp文件實際上完成了工作;其他單位不需要知道它是如何工作的,只要它符合頭文件指定的「合同」即可。

我也建議一些更改,以避免可能的衝突:

  • 變化"time.h"別的東西;有一個名爲<time.h>的標準頭文件,很容易讓您的編譯器或系統環境設置稍微錯誤,並最終包含錯誤的頭文件
  • 使用格式H_APPOINTMENT作爲標頭保護令牌。標識符以_開頭,後跟一個大寫字母;以及從E開始的全部標識符。