在转换中使用函子(带/不带构造函数)
Use of functor within transformation (with/without constructors)
在下面的类中定义构造函数方法有什么意义? 无论用户定义的构造函数如何,main 函数中转换中被调用函子的输出都是相同的。 关于模板和 STL 的课程使用此代码作为转换的示例,但包含构造函数,我认为这是不必要的。 函子的目标是将传递的每个字符串中的第一个字符大写,但如果实际使用/调用构造函数方法,则它将无法基于此处的实现正常运行。 当直接从类调用函子而不事先创建对象时,构造函数方法的功能是什么?
#include <cctype>
class title_case {
char _last;
char _sep = 0;
public:
// title_case() : _last(0) {}
// title_case(const char c) : _last(1), _sep(c) {}
const char operator() (const char c);
};
const char title_case::operator() (const char c) {
// if(_sep) _last = (!_last || _last == _sep) ? toupper(c) : c;
_last = (!_last || isblank(_last)) ? toupper(c) : c;
return _last;
}
int main()
{
string s1 = "this is a string";
cout << s1 << endl;
string s2(s1.size(), '.');
transform(s1.begin(), s1.end(), s2.begin(), title_case());
cout << s2 << endl;
return 0;
}
如果构造函数中未初始化_last
_last = (!_last || isblank(_last)) ? toupper(c) : c;
将是UB。
相关文章:
- 构造函数和转换运算符之间的重载解析
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- enable_if转换构造函数(静态强制转换,is_base_of)
- 参数包构造函数在类模板中隐藏用户定义的转换
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 复制构造函数隐式转换问题
- 没有合适的构造函数可以从"float"转换为"_D3DCOLORVALUE"
- 如果存在从"双精度"到"T"的转换,则禁用构造函数
- C++隐式构造函数转换,后跟类型向上转换
- 此语法中的构造函数转换错误
- C 操作员在具有构造函数转换时过载
- 如何在允许拷贝限制的同时禁用隐式构造函数转换
- 构造函数转换
- 通过构造函数转换容器
- C++ "没有合适的构造函数可以从<默认构造函数>转换为参数化构造函数
- 多个隐式构造函数转换
- (涉及显式)运算符和构造函数转换的优先级
- 构造函数转换如何在C++中工作
- 如何修复GCC编译中的const char *构造函数转换链错误
- 隐式构造函数转换的编译器优化