c++ - 布尔函数在 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 条件下),该函数也应该可以工作。你能给我一些关于为什么有人会使用它的理由吗?
解决方案
在您的示例代码中,实际上没有调用NotFindG
,因此确实不需要它。
bool 函数的通用Not*
变体用途有限,但我可以提出一些理由:
- 它存在的危害很小;如果来电者觉得使用它更好,那就继续吧。
- 它可能在一系列类似的功能中,所以即使这个特定的功能看起来没有必要,也只是与某种风格保持一致。
FindG
看起来特定于某种业务逻辑,这意味着尽可能多地包装它可能是一个好主意。MaybeNotFindG
是一个特定的要求,理论上可能不是FindG
,因此在技术上调用NotFindG
比!FindG
. 哎呀FindG
,如果是这种情况,也许应该删除。
推荐阅读
- ios - 向有限数量的用户分发 iOS 应用程序
- mysql - SEQUELIZE - 按关联模型的平均值排序
- javascript - 使用 JS/AJAX 提交复选框而不刷新
- android - 您将如何在 Utils/Helper 类中使用 AsyncTasks
- c# - 在视图模型中显示模型变量
- python - Colab 到 Google 云端硬盘:如何仅将新文件复制到云端硬盘?
- sql - 获取周开始日期
- .net-core - ADFS 2016 代流:无法获取任何用户信息
- python - npm install -g truffle install visual studiosVsCode
- php - Laravel 与外键条件的关系(在关系上切换外键)