微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法禁止一个函数被多次调用?

如何解决有没有办法禁止一个函数被多次调用?

我正在制作一个终端应用程序只是为了提高我的 OOP 技能。我有这个RunApplication()函数LoginCustomer()函数来让客户登录到应用程序。

代码是我的RunApplication函数

void RunApplication(){
    while (key!='q'){
    printUI();
    std::cin >> key;
    if (key == '1'){
        LoginCustomer();
    } 
    ..... // There are many other if statements but not included here since there are many and irrelevant.

这是我的LoginCustomer函数

void LoginCustomer(){
    std::cout << "***************************" << std::endl;
    std::cout << "1 ----> Show Available Cars" << std::endl;
    std::cout << "2 ----> Show Available Motors" << std::endl;
    std::cout << "3 ----> Show Available Trucks" << std::endl;
    std::cout << "always 'l'  ----> logout" << std::endl;
    std::cout << "always 'q'  ----> Exit" << std::endl;
    std::cout << "***************************" << std::endl;    
    std::cin >> key;
    if (key == 'l') //if you want to go back main page which was loaded into terminal with RunApplication() 
        return;
    else if(key == 'q')
        exit(EXIT_FAILURE);
}
        return; // What if I just call RunApplication() here again instead a simple return,wouldn't program be the most inefficient program ?
    else if(key == 'q')
        exit(EXIT_FAILURE);

我的问题是我可以禁止一个程序(或主程序)中多次调用一个函数吗?因为如果您考虑一下,在 LoginCustomer 中,如果您按“l”,只需使用 LoginCustomer() 命令结束 return 即可进入主页。但是,如果我只是在那里再次使用 RunApplication() 而不是 returncommand 会不会导致程序效率低下?所以我在想是否有任何keyword禁止函数被多次调用

解决方法

我的问题是我可以禁止在一个程序(或主程序)中多次调用一个函数吗?

您可以使用局部 static 变量来保证代码只被调用一次。

示例:

struct FunctionObject
{
    FunctionObject()
    {   
        std::cout << "I will be called only once" << std::endl;
    }   
};

void Do()
{
    static FunctionObject fo; 
}


int main()
{
    std::cout << "First" << std::endl;
    Do();
    std::cout << "Second" << std::endl;
    Do();
}

但是对于您的 UI 示例,我更喜欢具有简单状态机的设计,该设计注意状态只能按给定顺序激活。

我正在制作一个终端应用程序只是为了提高我的 OOP 技能。

您的示例代码没有任何对象,也没有任何 OOP 设计。也许您在其他地方有一些类/对象,但我在您的代码中看不到任何 OOP 设计。

,

您可以使用std::call_oncehttps://en.cppreference.com/w/cpp/thread/call_once

static std::once_flag flag;
std::call_once(flag,[]{
    //code here..
});
,

局部变量在栈上存储和创建。静态局部变量是常量并且在调用之间保持不变:

bool my_one_off_function ()
{
    static int iCount = 0;    //  static only intialized at start of program

    if  (! iCount++)          //  First time only will be zero
    {
        do_first_call_stuff ();
        return true;
    }
    else
        return false;
}

或者,在您的特定情况下,当收到登录请求时,您可以在调用登录函数之前检查登录凭据是否已经存在。这将是更“优雅”的解决方案,因为它允许注销等。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。