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

C++ 如何限制从主函数访问类函数?,c++,function,class,C++,Function,Class,如何限制从主函数访问类函数 这是我的密码 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

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

这是我的密码

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;
}
对不起,我的英语很差


编辑: 我没有删除旧代码,但用新代码扩展。 我认为这个案例不能使用friend类。因为我计划在每节课上使用。谢谢

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

Foo
成为
Bar

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

同时避免将成员变量
公开
。使用
setters/getter
代替使
Foo
成为
Bar

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

同时避免将成员变量
公开
。使用
setters/getter
代替你可以将Foo定义为Bar的好友类,并将doSomething()设置为私有。

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

Foo
内部将
Bar
设置为私有,不是吗?
那么,只有类
Foo
可以使用
bar

Foo
内部创建
bar
私有将起到作用,不是吗? 那么只有类
Foo
可以使用
bar