gpt4 book ai didi

c++ - 嵌套枚举的前向声明

转载 作者:IT老高 更新时间:2023-10-28 22:21:25 27 4
gpt4 key购买 nike

我有类似下面的代码:

class B
{
}

class A
{
enum {
EOne,
ETwo
} EMyEnum;

B myB;
}

我想在 B 类中声明一个 EMyEnum 类型的成员(在 A 之前声明)。这可能吗?我意识到解决方案是先声明 B 类,但为了清楚起见,我不想这样做。

最佳答案

这是不可能的......但它可以通过继承滥用来伪造:)

namespace detail
{
class A_EMyEnum
{
public:
enum {
EOne,
ETwo
} EMyEnum;

protected:
A_EMyEnum() {}
A_EMyEnum(const A_EMyEnum&) {}
A_EMyEnum& operator=(const A_EMyEnum&) { return *this; }
~A_EMyEnum() {}
}; // class A_EMyEnum
} // namespace detail

class B { // use detail::A_EMyEnum };

class A: public detail::A_EMyEnum
{

B mB;
};

另一方面...你为什么不简单地转发声明 B ?

class B;

class A
{
public:
enum EMyEnum {};

A();
A(const A&);
A& operator=(const A&);
~A();
void swap(A&);

private:
B* mB;
};

class B { // use A::EMyEnum };

当然,您需要实际编写 A 的所有通常“默认生成”的方法,但是,这并不需要花费这么多!

关于c++ - 嵌套枚举的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2238170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com