命名空间内类的循环依赖问题

Cyclic Dependency Issue with Class inside Namespace

本文关键字:依赖 问题 循环 命名空间      更新时间:2023-10-16

我遇到了循环依赖问题。我有两个头文件,它们各自相互依赖。我遇到的问题与命名空间中的类有关。

文件 #1

class Player; // This is how I forward declare another class
namespace sef {
class Base
{
   public:
   Player a;
   bool SendEvent(int eventType);
};
class Sub: public Base
{
    protected:
    Player b;
    bool Execute(string a);
};
}

文件 #2

//class sef::Sub; // I am having trouble compiling this
class Player
{
   public:
      sef::Sub* engine; // I am having trouble compiling this
};

如何在文件 #2 中转发声明 sef::Sub 类?

首先,如果只声明类型,则只能使用指针或引用。

class Player; // declaration, not definition
class Base {
  Player* p;
};

其次,命名空间是可扩展的,因此您可以编写如下:

namespace Foo { class Player; }

并使用指针:

class Base {
  Foo::Player* p;
}