【问题标题】:Redefinition of a class in a header file在头文件中重新定义一个类
【发布时间】:2015-10-07 20:31:26
【问题描述】:

我正在尝试使用g++ 编译我的代码,但它抛出了这个编译器错误:

Enrollment.h:3:7: error: redefinition of class sict::Enrollment
Enrollment.h:3:7: error: previous definition of class sict::Enrollment

我的Enrollment.h:

namespace sict{
class Enrollment{
  private:
    char _name[31];
    char _code[11];
    int _year;
    int _semester;
    int _slot;
    bool _enrolled;
  public:
    Enrollment(const char* name , const char* code, int year, int semester ,  int time );
    Enrollment();
    void set(const char* , const char* , int ,int,  int , bool = false );

    void display(bool nameOnly = false)const;
    bool valid()const;
    void setEmpty();
    bool isEnrolled() const;
    bool hasConflict(const Enrollment &other) const; 
  };

}

有什么办法解决这个问题?

【问题讨论】:

    标签: c++ class redefinition


    【解决方案1】:

    问题可能是您的头文件(直接或间接)包含在同一个翻译单元中。您应该使用某种方法来避免在您的 cpp 中多次包含同一头文件。我更喜欢在头文件开头的#pragma once - 它不是标准的,但所有主要编译器都支持它。否则,您可以选择旧的包含警卫:

    #ifndef _Enrollment_h_
    #define _Enrollment_h_
    // Your header contents here
    #endif
    

    或使用编译指示:

    #pragma once
    // Your header contents here
    

    【讨论】:

      【解决方案2】:

      您需要使用一些包含防护。 #pragma once 或:

      #ifndef MY_FILE_H
      #define MY_FILE_H
          ....
      #endif //MY_FILE_H
      

      这是为了防止在包含此标头的每个文件中包含相同的代码(双重包含)。这将从本质上帮助预处理器。更多信息here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多