Single class has a Class Redefinition Error

后端 未结 4 1093
眼角桃花
眼角桃花 2021-01-04 19:00

I\'m new to C++, and I\'m having a problem with my class definitions in a header file. The code for the header file (Student.h) is:

#include 
u         


        
相关标签:
4条回答
  • 2021-01-04 19:30

    I prefer using

       #pragma once
    

    as the first line of a header file, instead of the defines. Even if this is non-standard, it does avoid name clashes and can reduce compile time.

    0 讨论(0)
  • 2021-01-04 19:43

    You're probably including the .h file twice, the first time it will define Student, the second it will try to redefine it.

    See the Wikipedia entry on include guards for a more extensive explanation of the problem and information on how to avoid it.

    In short, there are two ways to do it

    Version 1, #defined include guards

    #ifndef STUDENT_HPP
    #define STUDENT_HPP
    
    ...your code here...
    
    #endif
    

    Usually the #define is called some variation of the file name since it has to be different in every include file.

    Version 2, #pragma once

    #pragma once
    
    ...your code here...
    

    This pragma is (as most pragmas) not portable to all compilers, but some of the most important ones. It also has the advantage of not needing a manually assigned name.

    Which you use is up to you, but you most likely have to pick one :)

    0 讨论(0)
  • 2021-01-04 19:46

    You need header guards on that header file. It is presumably being included twice.

    Modify the header, adding these lines to the beginning and end.

    #ifndef STUDENT_H
    #define STUDENT_H
    
    // Put the entire contents of your header here...
    
    #endif
    

    The define doesn't need to be STUDENT_H... it just needs to be unique.

    With these directives added, the compiler will ignore all contents of the header file if it has already been parsed.

    Alternatively, while it is not standard C++, all major compilers will allow you to put a single

    #pragma once
    

    as the first line of the header to prevent it from being parsed multiple times.

    0 讨论(0)
  • 2021-01-04 19:53

    When I learnt c++ our professor said, the first two lines that you write in c++ class should always be #ifndef followed by #define. This prevents multiple definitions in header files

    http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html

    0 讨论(0)
提交回复
热议问题