The function call operator lets users pretend that the functionoid is a function. In the previous example, class RandomSequence is a functionoid. Unlike a standard function, RandomSequence can maintain state between calls without sharing that state between all of its callers. Functionoids often use the function call operator (operator()()) rather than a named member function such as next(). In the following code, next() has been replaced by operator()() in class RandomSequence. #include <iostream> using namespace std; class RandomSequence { public: RandomSequence(int initialSeed=1001) throw(); int operator()() throw(); <-- 1 protected: unsigned long current_; }; RandomSequence::RandomSequence(int initialSeed) throw() : current_(initialSeed) { } int RandomSequence::operator()() throw() { current_ = current_ * 22695477UL + 1; return int(current_ >> 12) & 0x7fff; }
Given an object of class RandomSequence called rand, users can now use rand() instead of rand.next(): int main() { RandomSequence rand; for (int i = 0; i < 10; ++i) cout << rand() << ' '; } |