【问题标题】:Forward Declaration of enum in a class ?类中枚举的前向声明?
【发布时间】:2023-03-27 19:44:02
【问题描述】:

我有两个抽象类,它们彼此拥有一个指针。我需要在其中一个类中使用另一个类的枚举,例如显示示例。 AFoo 持有 ABar,ABar 需要一个指向 AFoo 的指针来更新一些数据,还需要一个使用 AFoo 枚举的成员函数。

我记得曾经遇到过这个问题,但枚举没有,我最终做了内联声明。

我可以做一个嵌套类,但是还有其他方法可以避免吗?

AFoo.hpp:

#include ...

class AFoo;
enum AFoo::poo; --> not possible

#include "ABar.hpp"

class AFoo {
public:
  ...
 virtual void func() = O;
 enum poo {
  H,
  I,
  ...
 }
protected:
 ABar *bar_;
};

ABar.hpp

#include ...

class Abar;

#include "AFoo.hpp"

class ABar {
public:
 ...
 virtual AFoo::poo doing_some_stuff() = 0; --> Here is my problem (if i replace the return type with basic type i have no compilation problem)
protected:
 AFoo *foo_;
};

【问题讨论】:

  • C++11 的枚举类可以前向声明。

标签: c++ c++11 enums forward-declaration


【解决方案1】:

在AFoo.hpp中,不要包含ABar.hpp,只前向声明类:

class ABar;

另外,在 ABar.hpp 中,包含 AFoo.hpp 并且不要转发 ABarAFoo

【讨论】:

  • 这不是一个有效的前向声明。
【解决方案2】:

在 AFoo.hpp 中,删除

enum AFoo::poo; --> not possible

替换

#include "ABar.hpp"

class ABar;

另外,您的 enum 声明缺少分号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 2010-09-09
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多