c++ - 有没有办法让一个类函数只能从另一个类函数调用?
问题描述
我正在开发一个小的 2D“渲染器”,它使用从屏幕上的类读取的参数来绘制东西。绘图动作由一个大的 Renderer 类完成。因此 ObjectParameters 类和 MainDrawing 类之间存在数据转换。 我使用声明一个公共函数来使 MainDrawing 的调用成为可能。但它也可以被其用户调用,并使类对象不安全。
那么有没有办法让声明的类函数只能被另一个类调用(但是方法是公共的、私有的或受保护的)?
class ObjectParameters {
public:
COORD position;
int Width;
int Height;
COLORREF elemColor;
private:
int _zIndex;
public:
ObjectParameters();
~ObjectParameters();
/* This line is the code which won't be called by the user,
/* but MainDrawing class needs it for setting the layers.
/* I don't want to make it callable from user,
/* because it can occur errors. */
void Set_ZIndex(int newValue);
};
class MainDrawing {
public:
MainDrawing();
~MainDrawing();
/* Here will change the object's z-index to order the draw sequence,
/* so it calls the Set_ZIndex() function */
void AddThingsToDraw(ObjectParameters& object);
private:
/* OTHER CODES */
};
解决方案
使用friend
关键字:https ://en.cppreference.com/w/cpp/language/friend
// Forward declaration. So that A knows B exists, even though it's no been defined yet.
struct B;
struct A {
protected:
void foo() {}
friend B;
};
struct B {
void bar(A& a) {
a.foo();
}
};
int main()
{
A a; B b;
b.bar(a);
//a.foo(); Not allowed
}
推荐阅读
- java - 如果不为空则返回值
- c# - 当值为 null 或 Empty 时如何使用 linq 查询处理值
- pine-script - 如何用两个时间坐标和两个价格坐标绘制趋势线
- reactjs - npx create-react-app 不工作“必须使用导入来加载 ES 模块:”
- hadoop - 如何在 Hadoop 集群上运行 Hadoop Streaming?
- google-colaboratory - 如何从 Google colab 打开和处理存储在 Google 云端硬盘中的文件?
- r - 为什么在 sapply 中包装 as.Date() 返回数字数据类型,而 lapply 返回日期数据类型?
- python - 如何使用 Python 从网站中提取逗号、句点或 colin 之前的所有文本
- flutter - http请求中的flutter ClientException
- php - 在php中获取服务器的根路径