[英]How to limit access to class function from main function?
如何限制从主函数访问类函数?
这是我的代码。
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。对不起,我英语不好。
编辑 :我没有删除旧代码,但我扩展了新代码。 我认为这种情况不能使用好友类。 因为我计划将其用于所有课程。 谢谢
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(){}
};
并且避免public
成员变量。 使用setters/getters
代替
您可以将Foo定义为Bar的朋友类,并将doSomething()设为私有。
在Foo
内部将Bar bar
Foo
私有可以解决问题,不是吗? 然后只有Foo
类可以使用bar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.