【问题标题】:C++ "Importing" an enum class from another C++ fileC++ 从另一个 C++ 文件“导入”一个枚举类
【发布时间】:2019-06-22 02:27:20
【问题描述】:

我来自 Java 背景,所以请多多包涵 :)

我正在尝试从另一个 C++ 文件“导入”(使用 Java 术语)enum class,以便能够直接使用它,而无需在其前面加上类名。

例如,假设我在头文件中有这个:

class Foo
{
    public:
        enum class Bar {ITEM_1, ITEM_2};
        void doThings(Bar bar);
};

现在,如果我想在另一个 C++ 文件中使用 Bar,我会这样做:

#include "Foo.h"

void Foo2::methodInAnotherFile()
{
    Foo foo();
    Foo::Bar bar = Foo::Bar::ITEM_2;
    foo.doThings(bar);
}

现在我想做的是能够做一些像“导入”(使用Java术语)Bar这样的事情,以便能够消除在Bar前面加上Foo::的需要,即做Bar bar = Bar::ITEM_2;

现在,由于我对 C++ 的了解有限,我能想到的一种方法是用 namespace FooNamespace{} 包围 Foo.h 中的所有代码,将 Bar 枚举从类中取出(但仍在命名空间),然后将using namespace FooNamespace 添加到Foo2 类的顶部。但是,对于我的应用程序来说,这真的没有多大逻辑意义,因为 Bar 枚举在逻辑上确实属于 Foo 类。

由于我精通 Java,这里有一个我想做的 Java 示例:

文件 1:

package org.fooclass;

public class Foo
{
    public static enum Bar
    {
        ITEM_1,
        ITEM_2;
    }

    public void doThings(Bar bar)
    {
        System.out.println("Item: " + bar.toString());
    }
}

文件 2:

package org.foo2class;

import org.fooclass.Foo;
import org.fooclass.Foo.Bar; //I want to do THIS in C++

public class Foo2
{
    public void methodInAnotherFile()
    {
        Foo foo = new Foo();

        /*
         * Since I've 'imported' Foo.Bar, I can now
         * use Bar directly instead of having to do this:
         * Foo.Bar bar = Foo.Bar.ITEM2;
         */
        Bar bar = Bar.ITEM_2;

        foo.doThings(bar);
    }
}

【问题讨论】:

    标签: c++ namespaces using


    【解决方案1】:

    通过using 语句使用type alias,例如:

    #include "Foo.h"
    
    using Bar = Foo::Bar; // <-- here
    
    void Foo2::methodInAnotherFile()
    {
        Foo foo;
        Bar bar = Bar::ITEM_2;
        foo.doThings(bar);
    }
    

    或者,限制其范围:

    #include "Foo.h"
    
    void Foo2::methodInAnotherFile()
    {
        using Bar = Foo::Bar; // <-- here
        Foo foo;
        Bar bar = Bar::ITEM_2;
        foo.doThings(bar);
    }
    

    【讨论】:

    • 我试过了,我得到这个编译错误:'Foo' is not a namespace or unscoped enum
    • 正确,是类名。请改用类型别名。 '使用 Bar1 = Foo::Bar;'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2010-12-22
    • 2012-07-07
    • 2016-11-10
    相关资源
    最近更新 更多