C++ Constructor Create Explicit one-arg constructor

Description

C++ Constructor Create Explicit one-arg constructor

#include <iostream>
using namespace std;
class Measure/* www. j  av  a2 s  .  c o  m*/
{
   private:
       const float MTF;          //meters to feet
       int feet;
       float inches;
   public:                      //no-args constructor
   Measure() : feet(0), inches(0.0), MTF(3.280833F)
   {  }
   //EXPLICIT one-arg constructor
   explicit Measure(float meters) : MTF(3.280833F)
   {
      float fltfeet = MTF * meters;
      feet = int(fltfeet);
      inches = 12*(fltfeet-feet);
   }
   void showdist()
   { cout << feet << "\'-" << inches << '\"'; }
};
int main()
{
   void fancyDist(Measure);    //declaration
   Measure dist1(2.35F);       //uses 1-arg constructor to convert meters to Measure
   // Measure dist1 = 2.35F;      //ERROR if ctor is explicit
   cout << "\ndist1 = "; dist1.showdist();
   float mtrs = 3.0F;
   cout << "\ndist1 ";
   // fancyDist(mtrs);             //ERROR if ctor is explicit
   return 0;
}
void fancyDist(Measure d)
{
   cout << "(in feet and inches) = ";
   d.showdist();
   cout << endl;
}



PreviousNext

Related