FAQ 16.13 How can the function call operator help with functionoids?

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; } 

(1) The name of the member function is operator()

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() << ' '; } 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net