简体   繁体   中英

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.


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

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

And also avoid making member variables public . Use setters/getters instead

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

Making Bar bar private inside Foo would do the trick, would it not? Then only the class Foo could use bar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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