简体   繁体   中英

Class Redefinition Error C++

I'm having an issue with a Class redefinition error. I was given a file "Arraylist.cpp" and "Arraylist.h". Oddly enough, the instructor included the Arraylist.h header guards in Arraylist.cpp as

#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

#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. On compile time I get "Class redefinition error" on 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. 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?

The guard should be in the header file.

Workaround (assuming you cannot edit the original header): Create another header file with guards and include the header file from there.

That is evil homework!

In any file including Arraylist.h:

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

The assignment is just misleading: The C/C++ preprocessor does text processing, only!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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