在下面的类中定义构造方法有什么意义? 无论用户定义的构造函数如何,主函数转换中被调用仿函数的输出都是相同的。 关于模板和 STL 的类(class)使用此代码作为转换示例,但包含构造函数,我认为这是不必要的。 仿函数的目标是将每个传递的字符串中的第一个字符大写,但如果实际使用/调用构造函数方法,它不会根据此处的实现正常运行。 当从类中直接调用仿函数而不事先创建对象时,构造函数方法的功能是什么?
#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 || isblank(_last)) ? toupper(c) : c;
如果 _last
未在构造函数中初始化,则为 UB。
关于c++ - 在转换中使用仿函数(带/不带构造函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862131/