简体   繁体   English

如何限制从主函数访问类函数?

[英]How to limit access to class function from main function?

How to limit access to class function from main function? 如何限制从主函数访问类函数?

Here my code. 这是我的代码。

class Bar
{
public: void doSomething(){}
};

class Foo
{
public: Bar bar;
//Only this scope that bar object was declared(In this case only Foo class)
//Can access doSomething() by bar object.
};

int main()
{
    Foo foo;
    foo.bar.doSomething(); //doSomething() should be limited(can't access)
    return 0;
}

PS.Sorry for my poor English. PS。对不起,我英语不好。


Edit : I didn't delete old code but I expand with new code. 编辑 :我没有删除旧代码,但我扩展了新代码。 I think this case can't use friend class. 我认为这种情况不能使用好友类。 Because I plan to use for every class. 因为我计划将其用于所有课程。 Thanks 谢谢

class Bar
{
public:
    void A() {} //Can access in scope that object of Bar was declared only
    void B() {}
    void C() {}
};

class Foo
{
public:
    Bar bar;
    //Only this scope that bar object was declared(In this case is a Foo class)
    //Foo class can access A function by bar object

    //main function need to access bar object with B, C function
    //but main function don't need to access A function
    void CallA()
    {
        bar.A(); //Correct
    }
};

int main()
{
    Foo foo;
    foo.bar.A(); //Incorrect: A function should be limited(can't access)    
    foo.bar.B(); //Correct
    foo.bar.C(); //Correct
    foo.CallA(); //Correct
    return 0;
}

Make Foo a friend of Bar Foo成为Bar的朋友

class Bar
{
    friend class Foo;
private:
    void doSomething(){}
};

And also avoid making member variables public . 并且避免public成员变量。 Use setters/getters instead 使用setters/getters代替

您可以将Foo定义为Bar的朋友类,并将doSomething()设为私有。

Making Bar bar private inside Foo would do the trick, would it not? Foo内部将Bar bar Foo私有可以解决问题,不是吗? Then only the class Foo could use bar . 然后只有Foo类可以使用bar

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

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