繁体   English   中英

有什么方法可以使 class function 只能从另一个 class ZC1C425268E68385D1AB5074F 调用

[英]Is there any way to make a class function only callable from another class function?

我正在开发一个小的 2D“渲染器”,它使用从屏幕上的类读取的参数来绘制事物。 绘图动作由大型渲染器 class 完成。 因此 ObjectParameters class 和 MainDrawing class 之间存在数据转换。 我用来声明一个公共 function 以使来自 MainDrawing 的调用成为可能。 但它也可以由其用户调用,并使 class object不安全

那么有什么方法可以使声明的 class function只能由另一个 class 调用(但是方法是公共的、私有的或受保护的)?

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
}

您可以将私有 function 设为嵌入式 class 的私有成员,如下所示:

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

我得到的是您希望继承的 class 无法访问父 class 变量。 为此,您只需将变量设为私有并将 function 设为公开即可。 并继承 class 作为保护,以便只有子 class 可以访问和使用 function。 如果您想要代码,我也可以提供帮助。 第一种方法是声明它受保护并继承 class。

    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()私有,因此只有朋友 class 可以访问它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM