简体   繁体   中英

C++ - Use enum from different header file, same namespace

I want to be able to use an enum class that is defined in one file, and used in others. When I try I only get this error: enum "Animal" has no member "Lion"

I can't find any posts that answer my question.

Here is an example of what I have in mind:
zooanimals.h

#pragma once

namespace Zoo
{
    enum class Animal;
}

zooanimals.cpp

#include "zooanimals.h"

namespace Zoo
{
    enum class Animal
    {
        Lion,
        Elefant,
        Monkey
    };
}

zoo.h

#pragma once

namespace Zoo
{
    class Visitor;
}

zoo.cpp

#include "zoo.h"
#include "zooanimals.h"

namespace Zoo
{
    class Visitor
    {
        Animal favoriteAnimal = Animal::Lion;
    };
}

You don't split enums in declaration and definition, so

enum class Animal
{
    Lion,
    Elefant,
    Monkey
};

should be in the header, not in a source file.

Remember, when you include a header into a source file, this source file can only "see" what is declared in this header. In your case, when the compiler processes zoo.cpp, it can not "see" the values of Animal , because they are not in the header.

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