项目PA,h .:

#include "Common.h"

class PA
{
   void func()
   {
     Common::getInstance()->cm();
     Common::getInstance()->onlyCallByPA();
   }
}


项目Common,Common.h:

class Common
{
    SINGLETON
public:
  void cm(){}
 private:
    //I do not want PB to call onlyCallByPA
    //so I want to add class PA to friend class
    //so I need to include PA.h
    //but if I include PA.h, PB.cpp  include PA.h
    //this will make PA.h expose to PB
    //I do not want PB to include PA.h
  void onlyCallByPA(){}
}


项目B,PB.cpp:

#include "Common.h"

class PB
{
    //I need to call cm() but PB do not be allowed to call onlyCallByPA
    //and also do not be allowed to include PA.h
}


因此,我想将PA用作Common的朋友类,但这将导致对PB的依赖。
有更好的解决方案吗?或者,我可以使用其他设计来实现我想要的吗?

最佳答案

使用前向声明。这将使您可以声明友谊,而无需包括标题或依靠PA的完整类声明。

普通h

class PA; // forward declaration.

class Common
{
    friend PA;
};

关于c++ - 如何使用 friend 类,但引入更少的依赖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17181682/

10-12 23:56