gpt4 book ai didi

c++ - 单个类出现类重定义错误

转载 作者:可可西里 更新时间:2023-11-01 16:25:58 31 4
gpt4 key购买 nike

我是 C++ 新手,头文件中的类定义有问题。头文件(Student.h)的代码是:

#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 类的前两行存在相同的错误。

我的编译中的任何地方都没有定义这两个类的 .c、.cpp 或 .h 文件。我不知道为什么会收到此错误。

最佳答案

你需要header guards在那个头文件上。它大概被包含了两次。

修改标题,将这些行添加到开头和结尾。

#ifndef STUDENT_H
#define STUDENT_H

// Put the entire contents of your header here...

#endif

定义不需要是STUDENT_H...它只需要是唯一的。

添加这些指令后,如果头文件已经被解析,编译器将忽略所有内容。

或者,而it is not standard C++ , 所有主要的编译器都允许你放一个

#pragma once

作为头部的第一行,以防止它被多次解析。

关于c++ - 单个类出现类重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8964164/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com