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
试试这个新来源:
#include <iostream>
struct Student {
std::string lastName;
std::string firstName;
};
Run Code Online (Sandbox Code Playgroud)
#include "student.h"
struct Student student;
Run Code Online (Sandbox Code Playgroud)
Edw*_*nge 17
你的student.h文件只转发声明一个名为"Student"的结构,它没有定义一个.如果您只通过引用或指针引用它,这就足够了.但是,只要您尝试使用它(包括创建一个),您将需要完整的结构定义.
简而言之,移动你的struct Student {...}; 进入.h文件并使用.cpp文件实现成员函数(它没有,所以你不需要.cpp文件).
Eri*_*ski 17
把它放在一个名为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;.