Jump to content

distance with +ve or -ve sign

- - - - -

  • Please log in to reply
No replies to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi

The given code compiles and runs okay. But would you like to recommend some changes? Please let me know. Thanks.


#include <iostream>

#include <cstdlib>


using namespace std;


enum posneg { pos, neg }; // as pogneg is enumeration, pos is given integer value 0 and neg 1

// and this fact is used in decision statements such (x==y). pos and neg aren't keywords in

// c++ for + and - rather we are taking advantage of enumerations which are treated ints internally


////////////////////////////////////////////////////////////////

class Distance

{

   protected: //in case member functions of derived classes need to access

      int feet;

      float inches;


   public:

      Distance() : feet(0), inches(0.0)

         {  }

      Distance(int ft, float in) : feet(ft), inches(in)

         {  }

      void getdist()

         {

         cout << "Enter feet: ";  cin >> feet;

         cout << "Enter inches: ";  cin >> inches;

         }

      void showdist() const //the function cannot the modify data members of obj which invokes it

         { cout << feet << "\'-" << inches << "\"" << endl; }

};

////////////////////////////////////////////////////////////////


class DistSign : public Distance

{

   private:

      posneg sign; //sign can take on two values


   public:

      DistSign() : Distance(), sign(pos)

         {/*empty body*/}

      DistSign(int ft, float in, posneg sg=pos) : Distance(ft, in), sign(sg)

         {/*empty body*/}


      void getdist()

	       {

	       Distance::getdist();

	       char ch;

	       cout << "Enter sign (+ or -): ";  cin >> ch;

	       sign = (ch=='+') ? pos : neg; //if statement is true, sign taken on 'pos'

	       }

      void showdist() const

	       {

	       cout << ( (sign==pos) ? "(+)" : "(-)" ); Distance::showdist();

	       }

};

////////////////////////////////////////////////////////////////


int main()

{

   DistSign dist1;

   dist1.getdist();


   DistSign dist2(11, 6.25);


   DistSign dist3(100, 5.5, neg);



   cout << "dist1 = ";  dist1.showdist();

   cout << "dist2 = ";  dist2.showdist();

   cout << "dist3 = ";  dist3.showdist();


   cout << endl;


   cout << (neg - pos) << endl; // proof enumerations are ints with first enumerator given 0 value


   system("pause;");

   return 0;

}


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users