Create member method to read value for member field - C++ Class

C++ examples for Class:Member Field

Description

Create member method to read value for member field

Demo Code

#include <iostream>
using namespace std;
class Measure/*from   w ww.  jav a  2 s.co  m*/
{
   private:
   int feet;
   float inches;
   public:
   void getdist()
   {
      cout << "\n   Enter feet: ";  cin >> feet;
      cout << "   Enter inches: ";  cin >> inches;
   }
   void showdist() const
   { cout << feet << "\'-" << inches << '\"'; }
};
int main()
{
   const int MAX = 100;
   Measure dist[MAX];
   int n=0;                       //count the entries
   char ans;                      //user response ('y' or 'n')
   cout << endl;
   do {                           //get distances from user
       cout << "Enter distance number " << n+1;
       dist[n++].getdist();        //store distance in array
       cout << "Enter another (y/n)?: ";
       cin >> ans;
    } while( ans != 'n' );      //quit if user types 'n'
    for(int j=0; j<n; j++)         //display all distances
    {
       cout << "\nMeasure number " << j+1 << " is ";
       dist[j].showdist();
    }
    cout << endl;
    return 0;
}

Result


Related Tutorials