【发布时间】:2021-06-05 05:03:31
【问题描述】:
我正在开发一个小型 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 */
};
【问题讨论】:
-
也许您可以使用
protected或public继承?还是friend函数声明?只是一个想法,我不知道这些是你的答案。 -
有点不清楚你到底要什么。您能否编写一些示例调用代码,以便我们了解在什么情况下您希望该函数可访问以及在什么情况下您希望该函数不可访问?