我的程序编译时有问题。我试着想了3-4个小时,但还是没找到解决办法。最后的结果是,我想要在多个struct students文件中使用.cpp,而不需要多个定义为..。你们能帮帮我吗?下面是代码:
student.h
#ifndef STUDENT
#define STUDENT
#include <string>
using namespace std;
extern int var;
struct students {
char CodSt[20];
string NumeSt;
string PrenSt;
string DenDisc1;
string MedCD1;
string DenDisc2;
string MedCD2;
string DenDisc3;
string MedCD3;
};
#endifgetStudents.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int var = 0;
extern struct students *student;
void getStudents() {
int i = 0;
ifstream ifs("Curenta.txt");
while(!ifs.eof()) {
ifs >> student[i].CodSt >> student[i].NumeSt >> student[i].PrenSt >> student[i].DenDisc1
>> student[i].MedCD1 >> student[i].DenDisc2 >> student[i].MedCD2 >> student[i].DenDisc3
>> student[i].MedCD3;
if(!ifs.eof()) {
i++;
}
var = i;
}
ifs.close();
}编译器错误:
In function 'void getStudents()':
[Error] invalid use of incomplete type 'struct students'
[Error] forward declaration of 'struct students'
and same, so on..提前谢谢。
发布于 2018-06-05 08:11:26
如果你想使用你的struct students,你应该把#include "student.h"文件变成你的.cpp文件。这样做会导致预编译器将头文件“插入”到源代码文件中,从而提供struct的正确定义。
一些关于您的代码的附带说明(请称我学究,但如果您很早就了解了这些规则,它将有助于您长期工作):
struct名为“`students”(复数),但包含的文件是'student.h‘(单数)。using namespace ...。原因是:如果某个人(一年后,当您忘记了这个文件的实现细节)拥有一个不同的string类,具有相似的语义,而不是标准库中的,那么该怎么办?如果这样的用户包括了那个students.h文件,那么“突然”所有的自定义string都变成了从标准库中提取出来的,确保了几天的调试乐趣:)extern struct students * student;文件中会有一个.cpp行。要么这是个错误,要么(如果不是)提供一个简短的评论来解释你为什么需要这一行是个好主意。https://stackoverflow.com/questions/50694978
复制相似问题