gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:56 26 4
gpt4 key购买 nike

如何限制主函数对类函数的访问?

这是我的代码。

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.抱歉我的英语不好。


编辑:我没有删除旧代码,而是使用新代码进行扩展。我认为这种情况不能使用 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 的 friend

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

同时避免将成员变量设为public。使用 setters/getters 代替

关于c++ - 如何限制从主函数访问类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11970474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com