I am trying to make a C++ program that uses multiple classes (and multiple header files). I have made an enum type called 'move' in one of the classes but I need to access this type from all of the classes. If I leave the enum declaration in just one header file, the other classes can't access it, the compiler gives an error everywhere its used except in that class and main. If I declare it in main, no class can access it. If I declare it in every class header file, I get a compiler error for redefining it.

Where do I declare an enum type so that every class header file has access to it?

有帮助吗?

解决方案

Where do I declare an enum type so that every class header file has access to it?

In its own header. Make a separate header file for your enum, and #include that header in all other headers that need to use it. Don't forget to add include guards to avoid multiple inclusions:

#ifndef MOVE_H
#define MOVE_H

enum move foo {
    LEFT, RIGHT, UP, DOWN
};

#endif /* MOVE_H */

Note: If you have multiple enumerations that logically belong together, or an enum that belongs together with a class, you may want to put the two in the same header.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top