我想知道是否以及如何在类成员函数中定义一个函数对象以直接使用它,例如 std::transform 函数。
我知道这个例子有点愚蠢,它只是为了展示我面临的问题。
文件“example.h”
class Example {
public:
//.. constructor and destructor stuff
std::string toString() const; //Converts 'mVal' to a std::string
private:
std::vector<int> mVal; //Only one digit numbers are allowed ([0-9])
}
文件“example.cpp”
std::string Example::toString() const
{
//The functor which should be used in std::transform
struct {
char operator()(const int number) {
char c;
//"Convert" 'number' to a char
return c;
};
} functor;
//Transform the integers to char
std::string str(mVal.size(), '0'); //Allocate enough space
std::transform(mVal.begin(), mVal.end(), str.begin(), functor);
return str;
};//toString()
自从我尝试直接在“example.cpp”中的成员函数内部实现函数对象以来,代码就没有被编译。我得到的错误信息是:
error: no matching function for call to ‘transform(__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, Example::toString() const::<anonymous struct>&)’
所以我认为在std::transform中使用struct“functor”时会出现问题。有人可以告诉我问题是什么吗?
使用:
Ubuntu Linux下的gcc-4.2编译器。
在此先感谢,
勒内。