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

问题描述 投票:0回答:1
#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
1个回答
1
投票

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

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

  • 它对现有的危害很小;如果呼叫者觉得最好使用它,请继续。
  • 它可能具有一系列类似的功能,因此即使似乎不需要该特定功能,也只是与某种样式保持一致的问题。
  • FindG看起来特定于某种业务逻辑,这意味着尽可能多地包装可能是个好主意。也许NotFindG是一个特定的要求,理论上可能不是FindG,因此从技术上讲,比NotFindG调用!FindG更准确。遇到这种情况,也许FindG是应该删除的那个。
© www.soinside.com 2019 - 2024. All rights reserved.