C++ program for typecast from class type to basic data type

//type cast F=W where W is an object of Weight and F is float value representing object W in kg only
//Weight has kg and g as data members

#include <iostream>
using namespace std;
class Weight
{
    int kg,g;
    public:
        Weight()
        {
            kg=g=0;
        }
        Weight(int kilogram,int gram)
        {
            kg=kilogram;
            g=gram;
        }
        operator float()
//conversion function
        {
            float f=kg+(float)g/1000;
            return f;
        }
};
int main()
{
    Weight W(12,400);
    float F=float(W);
    cout<<"All weight is "<<F;
    return 0;
}

No comments:

Post a Comment