问题描述
我是C ++的新手,我的头文件中的类定义有问题.头文件(Student.h)的代码为:
I'm new to C++, and I'm having a problem with my class definitions in a header file.The code for the header file (Student.h) is:
#include <string>
using namespace std;
class Student
{
// Data Members for a Student
string id;
string preferences[3];
int skill;
// Constructor
public:
Student(){}
public:
void SetID(string str)
{ this->id = str; }
public:
void SetSkill(int i)
{ this->skill = i; }
public:
void SetPreferences(int i, string s)
{
this->preferences[i] = s;
}
};
class StudentSchedule
{
public:
StudentSchedule(){}
};
编译器错误表明,第14行(Student类)是对'Student'的重新定义,而第15行({-Student类之后的开括号)是对'Student'的先前定义.StudentSchedule类在前两行中存在相同的错误.
The compiler error says that line 14 (class Student) is a redefinition of 'Student', and that line 15 ({ -- the open brace following class Student) is the previous definition of 'Student'.The same error on the first two consecutive lines exists for the StudentSchedule class.
在我的编译中定义任何一个类的任何地方,都没有.c,.cpp或.h文件.我不知道为什么会收到这个错误.
I have no .c, .cpp, or .h files anywhere in my compilation that define either class. I have no idea why I'm getting this error.
推荐答案
您需要 标题保护 放在该头文件上.大概两次.
You need header guards on that header file. It is presumably being included twice.
修改标题,将这些行添加到开头和结尾.
Modify the header, adding these lines to the beginning and end.
#ifndef STUDENT_H
#define STUDENT_H
// Put the entire contents of your header here...
#endif
定义不必为STUDENT_H
...它只需是唯一的即可.
The define doesn't need to be STUDENT_H
... it just needs to be unique.
添加了这些指令后,如果已经解析了头文件,编译器将忽略头文件的所有内容.
With these directives added, the compiler will ignore all contents of the header file if it has already been parsed.
或者,虽然它不是标准C ++ ,但是所有主要的编译器都允许您将单人
Alternatively, while it is not standard C++, all major compilers will allow you to put a single
#pragma once
作为标题的第一行,以防止对其进行多次分析.
as the first line of the header to prevent it from being parsed multiple times.
这篇关于单个班级有班级重新定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!