Reliable Software Logo

C++ In Action: Language

Exercise Solutions

  1. Here are the basic classes.
    class Sieve
    {
    public:
        virtual int NextNumber () = 0;
    };
    
    class SourceSieve: public Sieve
    {
    public:
        SourceSieve () : _i (1) {}
        int NextNumber ();
    private:
        int _i;
    };
    
    class Sieve2: public Sieve
    {
    public:
        Sieve2 (Sieve & src) : _src (src) {}
        int NextNumber ();
    private:
        Sieve & _src;
    };
    Here's the implementation of NextNumber for SourceSieve and Sieve2:
    int SourceSieve::NextNumber ()
    {
        if (_i > 100)
            return -1; // end
        return _i++;
    }
    
    int Sieve2::NextNumber ()
    {
        int i;
        do
        {
            i = _src.NextNumber ();
        } while (i % 2 == 0 && i != 2 && i != -1);
        return i;
    }
    This is main which prints all prime numbers less than 100:
    int main ()
    {
        SourceSieve src;
        Sieve2 s2 (src);
        Sieve3 s3 (s2);
        Sieve5 s5 (s3);
        Sieve7 s7 (s5);
        int i;
        for (;;)
        {
            i = s7.NextNumber ();
            if (i == -1)
                break;
            std::cout << i <<" ";
        }    
    }