问题描述
我一直试图在student.h
文件中包含一个称为学生"的结构,但是我不太确定该怎么做.
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.
我的student.h
文件代码完全由以下部分组成:
My student.h
file code consists of entirely:
#include<string>
using namespace std;
struct Student;
,而student.cpp
文件完全由以下内容组成:
while the student.cpp
file consists of entirely:
#include<string>
using namespace std;
struct Student {
string lastName, firstName;
//long list of other strings... just strings though
};
不幸的是,使用#include "student.h"
的文件会出现许多错误,例如
Unfortunately, files that use #include "student.h"
come up with numerous errors like
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
似乎编译器(VC ++)无法从"student.h"识别struct Student?
It appears the compiler (VC++) does not recognize struct Student from "student.h"?
如何在"student.h"中声明struct Student,以便仅#include"student.h"并开始使用该结构?
How can I declare struct Student in "student.h" so that I can just #include "student.h" and start using the struct?
推荐答案
您不应在头文件中放置using
指令,它会创建不必要的头痛.
You should not place an using
directive in an header file, it creates unnecessary headaches.
此外,您还需要在标头中添加包括卫士.
Also you need an include guard in your header.
当然,在解决了包含保护问题之后,您还需要在头文件中完整声明学生.正如其他人所指出的那样,在您的情况下,前瞻性声明是不够的.
of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
这篇关于C ++,如何在头文件中声明结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!