C++,如何在头文件中声明结构

wro*_*ame 22 c++ struct header include header-files

我一直试图在student.h文件中包含一个名为"student"的结构,但我不太清楚如何做到这一点.

我的student.h文件代码完全包含:

#include<string>
using namespace std;

struct Student;
Run Code Online (Sandbox Code Playgroud)

student.cpp文件完全由以下内容组成:

#include<string>
using namespace std;

struct Student {
    string lastName, firstName;
    //long list of other strings... just strings though
};
Run Code Online (Sandbox Code Playgroud)

不幸的是,使用的文件#include "student.h"会出现很多错误

error C2027: use of undefined type 'Student'

error C2079: 'newStudent' uses undefined struct 'Student'  (where newStudent is a function with a `Student` parameter)

error C2228: left of '.lastName' must have class/struct/union 
Run Code Online (Sandbox Code Playgroud)

编译器(VC++)似乎无法识别"student.h"中的struct Student?

如何在"student.h"中声明struct Student,以便我可以#include"student.h"并开始使用struct?

Zai*_*Zai 26

试试这个新来源:

student.h

#include <iostream>

struct Student {
    std::string lastName;
    std::string firstName;
};
Run Code Online (Sandbox Code Playgroud)

student.cpp

#include "student.h"

struct Student student;
Run Code Online (Sandbox Code Playgroud)


bao*_*aol 19

您不应该using在头文件中放置指令,它可能会在将来给您带来问题.

你的标题中还需要一个包含守卫.

编辑:当然,在修复了包含保护问题之后,您还需要在头文件中完整地声明学生.正如其他人所指出的那样,前瞻性声明在你的案件中是不够的.

  • -1.虽然这些都是真实的陈述,但我不知道它们中的任何一个如何解决问题中报告的错误消息. (6认同)
  • @rob这不是一个应该被接受的答案;)我只是认为他需要这两个建议。我相信我的回答与其他人关于前向声明的回答结合起来解决了问题。 (2认同)

Edw*_*nge 17

你的student.h文件只转发声明一个名为"Student"的结构,它没有定义一个.如果您只通过引用或指针引用它,这就足够了.但是,只要您尝试使用它(包括创建一个),您将需要完整的结构定义.

简而言之,移动你的struct Student {...}; 进入.h文件并使用.cpp文件实现成员函数(它没有,所以你不需要.cpp文件).


Eri*_*ski 17

C++,如何在头文件中声明一个struct:

把它放在一个名为main.cpp的文件中:

#include <cstdlib>
#include <iostream>
#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;
}
Run Code Online (Sandbox Code Playgroud)

把它放在一个名为student.h的文件中

#ifndef STUDENT_H
#define STUDENT_H

#include<string>
struct Student {
    std::string lastName, firstName;
};

#endif
Run Code Online (Sandbox Code Playgroud)

编译并运行它,它应该产生这个输出:

s1.firstName = "fred";
Run Code Online (Sandbox Code Playgroud)

专家提示:

您不应该using namespace std;在C++头文件中放置指令,因为您可能会导致不同库之间的静默名称冲突.要解决此问题,请使用完全限定名称: std::string foobarstring;而不是包含std命名空间string foobarstring;.