在转换中使用函子(带/不带构造函数)

Use of functor within transformation (with/without constructors)

本文关键字:构造函数 转换      更新时间:2023-10-16

在下面的类中定义构造函数方法有什么意义? 无论用户定义的构造函数如何,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。