cm(); -6ren">
gpt4 book ai didi

c++ - 如何使用 friend 类但引入较少的依赖

转载 作者:行者123 更新时间:2023-11-28 07:33:36 26 4
gpt4 key购买 nike

项目 A,PA.h:

#include "Common.h"

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

项目通用,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的依赖。
有更好的解决方案吗?或者,我可以使用其他设计来实现我想要的吗?

最佳答案

使用前向声明。这将允许您在不包含 header 或依赖 PA 的完整类声明的情况下声明友元。

通用.h

class PA; // forward declaration.

class Common
{
friend PA;
};

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

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