0

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;
}
4

3 回答 3

4

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

于 2012-08-15T13:49:52.787 回答
1

You can define Foo as a friend class of Bar and make doSomething() private.

于 2012-08-15T13:50:25.610 回答
1

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

于 2012-08-15T13:53:25.673 回答