如何限制从主函数访问类函数?
如何限制从主函数访问类函数?如何限制从主函数访问类函数?
在这里我的代码。
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.Sry for my poor English。
编辑: 我没有删除旧的代码,但我有新的代码扩展。 我认为这种情况下不能使用朋友类。因为我计划用于每个班级。由于
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()为私有。
回答:
制作Bar bar
private在Foo
会做的伎俩,不是吗? 然后只有类Foo
可以使用bar
。
以上是 如何限制从主函数访问类函数? 的全部内容, 来源链接: utcz.com/qa/264905.html