我们在C/C++编程中,经常出现这种类型的错误:error: redefinition of ‘struct student‘或者error: previous definition of ‘struct student‘。
字面来看,指的是重新定义或者先前已定义。下面我将针对这一类型问题给出一套系统的解决方案,看了以下文章后,相信以后对于这种问题将会胸有成竹,对于程序的设计也更加合理。
开门见山,我讲给出一个具体的例子。
struct student
{
char name[20];
int age;
};
#include "student.h"
#include <vector>
struct club
{
char name[20];
std::vector<student> members;
};
#include <iostream>
#include <cstring>
#include "student.h"
#include "club.h"
using namespace std;
int main()
{
club club1;
student stu1{"jin", 20};
student stu2{"shia", 19};
strcpy(club1.name, "gamelover");
club1.members.push_back(stu1);
club1.members.push_back(stu2);
for(auto stu:club1.members)
{
cout<<stu.name<<endl;
}
}
#ifndef STUDENT_H
#define STUDENT_H
struct student
{
char name[20];
int age;
};
#endif // STUDENT_H
#ifndef CLUB_H
#define CLUB_H
#include "student.h"
#include <vector>
struct club
{
char name[20];
std::vector<student> members;
};
#endif // CLUB_H
#include <iostream>
#include <cstring>
#include "student.h"
#include "club.h"
using namespace std;
int main()
{
club club1;
student stu1{"jin", 20};
student stu2{"shia", 19};
strcpy(club1.name, "gamelover");
club1.members.push_back(stu1);
club1.members.push_back(stu2);
for(auto stu:club1.members)
{
cout<<stu.name<<endl;
}
}
#pragma once
#include "club.h"
struct student
{
char name[20];
int age;
club myclub;
};#pragma once
class club;
struct student
{
char name[20];
int age;
club myclub;
};
但是我们发现还是错误!!这次错误是:error: field ‘myclub‘ has incomplete type。其实是因为club这里还没有定义,并不知道其大小,myclub大小未知。我们稍作改变:#pragma once
class club;
struct student
{
char name[20];
int age;
club *myclub;
};这样就可以了。原文:http://blog.csdn.net/jr19911118730/article/details/42816789