C++, how to declare a struct in a header file

后端 未结 7 1501
暖寄归人
暖寄归人 2021-01-30 14:40

I\'ve been trying to include a structure called \"student\" in a student.h file, but I\'m not quite sure how to do it.

My student.h file code c

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 14:43

    C++, how to declare a struct in a header file:

    Put this in a file called main.cpp:

    #include 
    #include 
    #include "student.h"
    
    using namespace std;    //Watchout for clashes between std and other libraries
    
    int main(int argc, char** argv) {
        struct Student s1;
        s1.firstName = "fred"; s1.lastName = "flintstone";
        cout << s1.firstName << " " << s1.lastName << endl;
        return 0;
    }
    

    put this in a file named student.h

    #ifndef STUDENT_H
    #define STUDENT_H
    
    #include
    struct Student {
        std::string lastName, firstName;
    };
    
    #endif
    

    Compile it and run it, it should produce this output:

    s1.firstName = "fred";
    

    Protip:

    You should not place a using namespace std; directive in the C++ header file because you may cause silent name clashes between different libraries. To remedy this, use the fully qualified name: std::string foobarstring; instead of including the std namespace with string foobarstring;.

提交回复
热议问题