[英]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.