我想知道是否以及如何在類成員函數內部定義函數對象以便直接使用它,例如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編譯器。
在此先感謝,
勒內。
見http://stackoverflow.com/questions/2662843/c-can-local-class-reference-be-passed-to-a-function – 2010-08-05 08:47:09
可能重複[使用STL算法的本地類](http://stackoverflow.com/questions/742607/using-local-classes-with-stl-algorithms) – 2010-08-05 09:15:43
是的,你是對的。不知道確切的搜索字詞。 – PiJ 2010-08-05 09:31:18