Thursday 17 August 2017

Start with the COUNTEN2 program in this chapter. It can increment or decrement a counter, but only using prefix notation. Using inheritance, add the ability to use postfix notation for both incrementing and decrementing. (See Chapter 8 for a description of postfix notation.)



SOLUTION:
#include "stdafx.h"
#include "iostream"
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////
class Counter        
{
            protected:
                        unsigned int count;
            public:
                        Counter( ) : count( )
                                    { }
                        Counter(int c) : count(c)
                                    { }
                        unsigned int get_count( ) const
                        {
return count;
}
                        Counter operator ++ ( )
                        {
return Counter(++count);
}
};
class CountDn : public Counter
{
            public:
                        CountDn( ) : Counter( )
                                    { }
                        CountDn(int c) : Counter(c)
                                    { }
                        CountDn operator -- ( )
                        {
return CountDn(--count);
}
};
class post_inc_dec : public Counter
{
            public:
                        post_inc_dec( ) : Counter( )
                                    { }
                        post_inc_dec(int c) : Counter(c)
                                    { }
                        post_inc_dec operator ++ (int)
                        {
return post_inc_dec(count++);
}
                        post_inc_dec operator -- (int)
                                    { return post_inc_dec(count--); }
};
/////////////////////////////////////////////////////////////////////////////////////////
void main( )
{
            CountDn c1;
            CountDn c2(100);
            post_inc_dec c3(200);
            cout << "c1=" << c1.get_count( );
            cout << "\nc2=" << c2.get_count( );
            cout << "\nc3=" << c3.get_count( );
            ++c1;  
c1++;
++c1;
            cout << "\nc1=" << c1.get_count( );
            --c2;
            --c2;
            cout << "\nc2=" << c2.get_count( );
            c3--;
            c3++;
            c3++;
            c3++;
            post_inc_dec c4 = c3--;
            cout << "\nc3=" << c3.get_count( );
            cout << endl;
            system("pause");
}
OUTPUT:

0 comments: