简体   繁体   English

Class 重定义错误 C++

[英]Class Redefinition Error C++

I'm having an issue with a Class redefinition error.我遇到了 Class 重定义错误的问题。 I was given a file "Arraylist.cpp" and "Arraylist.h".我得到了一个文件“Arraylist.cpp”和“Arraylist.h”。 Oddly enough, the instructor included the Arraylist.h header guards in Arraylist.cpp as奇怪的是,讲师在 Arraylist.cpp 中包含了 Arraylist.h header 防护装置

#ifndef ARRLIST
#define ARRLIST
#include "Arraylist.h"
#endif

To me this makes sense even though it is really weird.对我来说这是有道理的,尽管它真的很奇怪。 Now I have a Stack and a Queue class that both inherit from Arraylist and have.cpp and.h files with proper header guards listed below现在我有一个堆栈和一个队列 class 都继承自 Arraylist 并且有 .cpp 和 .h 文件以及下面列出的正确 header 防护

#ifndef QUEUEARRLIST
#define QUEUEARRLIST
#include "Arraylist.h"
//Code
#endif

#ifndef STACKARRLIST
#define STACKARRLIST
#include "Arraylist.h"
//Code
#endif

In another class, I include both Stack.h and Queue.h.在另一个 class 中,我同时包含了 Stack.h 和 Queue.h。 On compile time I get "Class redefinition error" on Arraylist.cpp.在编译时,我在 Arraylist.cpp 上收到“类重新定义错误”。 Now, if move the header guards from Arraylist.cpp into Arraylist.h like any normal person would, I get no errors and everything runs fine.现在,如果像任何正常人一样将 header 防护装置从 Arraylist.cpp 移到 Arraylist.h 中,我不会出错,一切正常。 The problem is with the assignment we are not allowed to modify the instructors code at all, so is there any way to get around this, or should I tell the professor he should reconsider including the header guards in his.cpp file?问题在于我们根本不允许修改讲师代码的作业,所以有什么办法可以解决这个问题,还是我应该告诉教授他应该重新考虑在 his.cpp 文件中包含 header 保护?

The guard should be in the header file.防护应该在 header 文件中。

Workaround (assuming you cannot edit the original header): Create another header file with guards and include the header file from there.解决方法(假设您无法编辑原始标题):创建另一个带有保护的 header 文件,并从那里包含 header 文件。

That is evil homework!那是邪恶的功课!

In any file including Arraylist.h:在包括 Arraylist.h 在内的任何文件中:

#ifndef ARRLIST
#define ARRLIST
#include "Arraylist.h"
#endif

The assignment is just misleading: The C/C++ preprocessor does text processing, only!分配只是误导:C/C++ 预处理器只进行文本处理!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM