微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法让一个类函数只能从另一个类函数调用?

如何解决有没有办法让一个类函数只能从另一个类函数调用?

我正在开发一个小的 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
}
,

您可以使私有函数成为嵌入类的私有成员,如下所示:

class MyOuterClass
{
public:
    class MyInnerClass
    {
private:
        void MyPrivateFunction () {}
    public:
        void MyPublicFuncton ()
        {
            MyPrivateFunction ();
        }
    };
};
,

我得到的是你希望继承的类不能访问父类变量。为此,您可以简单地将变量设为私有并将函数设为公有。并将类继承为保护,以便只有子类可以访问和使用该功能。 如果您想要代码,我也可以提供帮助。 第一种方法是声明它受保护并继承该类。

    class ObjectParameters {
    
        public:
    int Width;
    
    int Height;
    
        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. */
    protected:
   

     void Set_ZIndex(int newValue);

    };

    class MainDrawing:ObjectParameters {

    public:
MainDrawing();

~MainDrawing();

Set_ZIndex(5);
    /* Here will change the object's z-index to order the draw sequence,/* so it calls the Set_ZIndex() function */
    private:
    /* OTHER CODES */
    };

第二种方法是在 ObjectParameters 中将 MainDrawing 声明为友元

friend class MainDrawing 并将函数 Set_ZIndex() 设为私有,以便只有朋友类可以访问它

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。