gpt4 book ai didi

c++ - 在头文件中重新定义一个类

转载 作者:太空狗 更新时间:2023-10-29 23:50:15 24 4
gpt4 key购买 nike

我试图用 g++ 编译我的代码,但它抛出了这个编译器错误:

Enrollment.h:3:7: error: redefinition of class sict::Enrollment
Enrollment.h:3:7: error: previous definition of class sict::Enrollment

我的Enrollment.h:

namespace sict{
class Enrollment{
private:
char _name[31];
char _code[11];
int _year;
int _semester;
int _slot;
bool _enrolled;
public:
Enrollment(const char* name , const char* code, int year, int semester , int time );
Enrollment();
void set(const char* , const char* , int ,int, int , bool = false );

void display(bool nameOnly = false)const;
bool valid()const;
void setEmpty();
bool isEnrolled() const;
bool hasConflict(const Enrollment &other) const;
};

}

有什么办法可以解决这个问题吗?

最佳答案

问题很可能是您的头文件包含(直接和间接)在同一个翻译单元中。您应该使用某种方式避免在您的 cpp 中多次包含同一头文件。我更喜欢在头文件的开头使用 #pragma once - 它不是标准的,但所有主要编译器都支持它。否则你可以去找老式的包括守卫:

#ifndef _Enrollment_h_
#define _Enrollment_h_
// Your header contents here
#endif

或附注:

#pragma once
// Your header contents here

关于c++ - 在头文件中重新定义一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001923/

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