//function declerations
void func_A();
void func_B();
void func_SubA();
//main
int main(){ ... }
//function definitions
void func_A(){ ... }
void func_B(){ ... }
void func_SubA(){ ... }
确保只能在 func_A() 内部调用 func_SubA() 的最佳方法是什么?
如果 func_B() 试图调用 func_SubA(),我希望收到编译器错误。
最佳答案
您可以将要限制访问的函数声明为类的私有(private)成员,然后使用友元来授予访问权限。
class Balloon
{
private: // private is the default. we just want to be explicit
friend void Ken();
friend void Barbie();
static void Pop();
};
void Ken() {
Balloon::Pop(); // We are allowed to pop it!
}
void Barbie() {
Balloon::Pop(); // We are allowed to pop it too!
}
void Jack() {
Balloon::Pop(); // Access Denied! we must be in a time out!
}
关于c++ - 如何使一个函数只能从另一个函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16753649/