Class to class conversion can be
done in source as well as
destination class. write a
program to support this.
#include <iostream>
using namespace std;
class Metrs
{
private:
int m_metrs;
public:
Metrs(int metrs = 0)
{
m_metrs = metrs;
}
operator int() { return m_metrs; }
int getMetrs() { return m_metrs; }
void setMetrs(int metrs) { m_metrs = metrs; }
};
class Santimetrs
{
private:
int m_santimetrs;
public:
Santimetrs(int santimetrs = 0)
{
m_santimetrs = santimetrs;
}
operator Metrs() { return Metrs(m_santimetrs / 100); }
};
void printMetrs(Metrs Metrs)
{
cout << Metrs;
}
int main()
{
// example class to class conversion
int a = 248;
double b = a; // an int value is implicitly converted to a double value
float c = 3.5;
int d = static_cast<int>(c);//an float value is explicitly converted to a int value
//example converting a class to a class inside a custom class
Santimetrs santi(678);
printMetrs(santi);//santi (Santimetrs) is implicitly converted to Metrs here
return 0;
}
Comments
Leave a comment