简体   繁体   English

C++ - 使用来自不同 header 文件的枚举,相同的命名空间

[英]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.我希望能够使用在一个文件中定义并在其他文件中使用的枚举 class。 When I try I only get this error: enum "Animal" has no member "Lion"当我尝试时,我只收到此错误: 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.应该在 header 中,而不是在源文件中。

Remember, when you include a header into a source file, this source file can only "see" what is declared in this header.请记住,当您将 header 包含到源文件中时,该源文件只能“看到”在此 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.在您的情况下,当编译器处理 zoo.cpp 时,它无法“看到” Animal的值,因为它们不在 header 中。

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

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