布尔函数在 C++ 中的使用

boolean function uses in c++

#include <iostream>
#include<string>

bool findG( const std::string name)
{
    return name.length() >= 3 && name[0] == 'H'; 
}

bool NotfindG( const std::string name)
{
    return !findG(name); 
}

int main()
{
    std::string name = "agHello";


    if(findG(name)) 
    {
        std::cout << "It found Hello\n";
    }
    else
    {
        std::cout << "It did not find hello \n";
    }
}

如果找到参数中给定的字符串,您会看到一个布尔函数 returns。

我了解函数的作用。我的兴趣是想知道上面代码中函数NotfindG的活动是什么?

bool NotfindG( const std::string name)
{
    return !findG(name); 
}

我看到有人在使用它,但对我来说,即使没有布尔函数 NotfindG(我的意思是在 else 条件下),该函数也应该可以工作。你能给我一些关于为什么有人会使用它的推理吗?

在您的示例代码中,实际上并没有调用 NotFindG,因此确实没有必要。

布尔函数的通用 Not* 变体用途有限,但我可以提出一些理由:

  • 现有的无害;如果来电者觉得使用它更好,那就继续吧。
  • 它可能在一系列类似的功能中,所以即使这个特定的功能看起来不是必需的,它只是与某种风格保持一致的问题。
  • FindG 看起来特定于某种业务逻辑,这意味着尽可能多地包装它可能是个好主意。也许 NotFindG 是一个特定的要求,理论上可以是 FindG 以外的其他东西,所以从技术上讲,调用 NotFindG 比调用 !FindG 更准确。如果是这种情况,也许 FindG 应该被删除。