我一直试图在student.h
文件中包含一个名为“student”的结构,但我不太清楚该怎么做。
我的student.h
文件代码完全由以下内容组成:
#include<string>
using namespace std;
struct Student;
而student.cpp
文件完全由以下内容组成:
#include<string>
using namespace std;
struct Student {
string lastName, firstName;
//long list of other strings... just strings though
};
不幸的是,使用#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
编译器(VC ++)似乎无法识别“student.h”中的struct Student?
如何在“student.h”中声明struct Student,以便我可以#include“student.h”并开始使用struct?
你不应该在头文件中放置一个using
指令,它会创建unnecessary headaches。
你的标题中还需要一个include guard。
编辑:当然,在修复了包含保护问题之后,您还需要在头文件中完整地声明学生。正如其他人所指出的那样,前瞻性声明在你的案件中是不够的。
试试这个新来源:
#include <iostream>
struct Student {
std::string lastName;
std::string firstName;
};
#include "student.h"
struct Student student;
您的student.h文件只向前声明一个名为“Student”的结构,它没有定义一个结构。如果您只通过引用或指针引用它,这就足够了。但是,只要您尝试使用它(包括创建一个),您将需要完整的结构定义。
简而言之,移动你的struct Student {...};进入.h文件并使用.cpp文件实现成员函数(它没有,所以你不需要.cpp文件)。
把它放在一个名为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;
}
把它放在一个名为student.h的文件中
#ifndef STUDENT_H
#define STUDENT_H
#include<string>
struct Student {
std::string lastName, firstName;
};
#endif
编译并运行它,它应该产生这个输出:
s1.firstName = "fred";
普罗蒂普:
您不应该在C ++头文件中放置using namespace std;
指令,因为您可能会导致不同库之间的静默名称冲突。要解决此问题,请使用完全限定名称:std::string foobarstring;
,而不是使用string foobarstring;
包含std命名空间。
您只在头文件中获得了student
的前向声明;你需要将struct声明放在头文件中,而不是.cpp。方法定义将在.cpp中(假设您有)。
好的,我注意到了三件大事
希望这可以帮助!
你不能。
为了“使用”结构,即能够声明该类型的对象并访问其内部,您需要结构的完整定义。因此,您想要执行任何操作(并且根据错误消息判断),您必须将结构类型的完整定义放入头文件中。