如何使用一个类的嵌套枚举作为另一个类的嵌套枚举?

发布于 2024-11-27 22:13:52 字数 385 浏览 1 评论 0原文

下面的代码将在 enum en = A::en; 行给出编译错误,但它描述了我想要做的事情(使 A 的嵌套枚举成为嵌套枚举B 也是如此)。

#include <iostream>
using namespace std;
struct A
{
    enum a_en{X = 0, Y = 1};
};
struct B
{
    enum b_en = A::a_en; //syntax error
};
int main()
{
    cout << B::X << endl;
    return 0;
}

所以问题是我怎样才能在 C++ 中做这样的事情?

The code bellow will give compile error on line enum en = A::en; but it describes what I want to do (to make nested enum of A to be nested enum of B as well).

#include <iostream>
using namespace std;
struct A
{
    enum a_en{X = 0, Y = 1};
};
struct B
{
    enum b_en = A::a_en; //syntax error
};
int main()
{
    cout << B::X << endl;
    return 0;
}

So the question is how can I do such thing in c++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼中杀气 2024-12-04 22:13:52

将枚举放在 A 和 B 都可以继承的基类中。

Put the enum in a base class that both A and B can inherit from.

倾城花音 2024-12-04 22:13:52

使用

struct B: A
{
};

而不是

struct B
{
    enum b_en = A::a_en;
};

Use

struct B: A
{
};

instead of

struct B
{
    enum b_en = A::a_en;
};
梦罢 2024-12-04 22:13:52

当类/结构以这种方式相关时,您应该继承它们。将公共枚举放在基类中,以便所有派生(相关)类都可以访问它。

MFC 的 CFile 类定义了枚举,CStdioFile 和其他派生类可以使用:

enum OpenFlags {
        modeRead =         (int) 0x00000,
        modeWrite =        (int) 0x00001,
...    };

When the classes/structs are related this way, you should inherit them. Put the public enum in base class so that all derived (related) classes can access it.

MFC' CFile class has enums defined, which CStdioFile and other derived classes can use:

enum OpenFlags {
        modeRead =         (int) 0x00000,
        modeWrite =        (int) 0x00001,
...    };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文