如何限制从main函数访问类函数?
这是我的代码。
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我的英语很差。
修改: 我没有删除旧代码,但我扩展了新代码。 我觉得这个案子不能用朋友班。因为我计划用于每个班级。感谢
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;
}
答案 0 :(得分:4)
让Foo
成为Bar
class Bar
{
friend class Foo;
private:
void doSomething(){}
};
还避免制作成员变量public
。请改用setters/getters
答案 1 :(得分:1)
您可以将Foo定义为Bar的朋友类,并将doSomething()设为私有。
答案 2 :(得分:1)
在Bar bar
内部Foo
私有化可以解决问题,不是吗?
然后,只有课程Foo
可以使用bar
。