【问题标题】:Multiple Definitions compiling errors多个定义编译错误
【发布时间】:2014-04-12 00:59:58
【问题描述】:

我在 StackExchange 上的第一篇文章! 我有一个 C++ 课程的作业;使用先前分配的日期类(月、日、年)和时间类(小时、分钟、上午/下午)进行约会类。 我想我已经解决了大部分主要/语法错误。

我的问题是,就我目前完成#includes 和头文件的方式而言,我得到一个多重定义错误 日期和时间的构造函数。(而且我对模板了解不多,但我必须使用它们。)

我的文件:

  • 约会.cpp

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

    我需要能够创建时间/日期对象,我应该使用 .h 还是 .cpp 文件?

  • 约会.h

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

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

    #ifndef _DATE_H_
    #define _DATE_H_
    
  • 时间.cpp

    #ifndef _TIME_CPP_
    #define _TIME_CPP_
    #include "time.h"
    
  • 时间.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;
    }
    
  • 读取.cpp

    #include "arrayListType.h"
    #include "appointment.h"
    #include <fstream>
    using namespace std;
    
    void read(arrayListType<Appointment>& appointments)
    {...}
    
  • 输出.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 个。如果我需要发布更多信息,我很高兴。我也有所有文件的压缩版本。

【问题讨论】:

  • 你正在使用reserved identifiers
  • 只包含头文件而不包含源单元
  • 我没有看到每个头文件各自的结束 #endif。他们在场吗?
  • 是的,我保留了#endif (s) 只是为了使帖子尽可能简短。
  • 删除 .cpp 包含现在会发生什么?

标签: c++ compiler-errors multiple-definition-error


【解决方案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" 更改为其他内容;有一个名为 &lt;time.h&gt; 的标准头文件,很容易让您的编译器或系统环境设置稍有错误并最终包含错误的文件
  • 使用H_APPOINTMENT 格式作为标头保护令牌。以_ 开头后跟一个大写字母的标识符被保留;以E 开头的全大写标识符也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多