首页 > 解决方案 > 布尔函数在 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";
    }
}

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

我了解该功能在做什么。我的兴趣是知道NotfindG上面代码中函数的活动是什么?

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

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

标签: c++boolean-operations

解决方案


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

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

  • 它存在的危害很小;如果来电者觉得使用它更好,那就继续吧。
  • 它可能在一系列类似的功能中,所以即使这个特定的功能看起来没有必要,也只是与某种风格保持一致。
  • FindG看起来特定于某种业务逻辑,这意味着尽可能多地包装它可能是一个好主意。MaybeNotFindG是一个特定的要求,理论上可能不是FindG,因此在技术上调用NotFindG!FindG. 哎呀FindG,如果是这种情况,也许应该删除。

推荐阅读