重新定义头文件中的类

时间:2015-10-07 20:31:27

标签: c++ class redefinition

我试图用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; 
  };

}

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:6)

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

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

或使用pragma:

#pragma once
// Your header contents here

答案 1 :(得分:2)

你需要使用一些包含警卫。 #pragma once或:

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

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

相关问题