#include <iostream>
using namespace std;
class Feet {
private:
int feet;
public:
Feet() {
feet = 0;
}
Feet(int f) {
feet = f;
}
// conversion operator to convert Feet to Meters
operator float() const {
return feet / 3.281; // 1 foot = 0.3048 meters
}
// display feet
void display() {
cout << feet << " feet" << endl;
}
};
class Meters {
private:
float meters;
public:
Meters() {
meters = 0;
}
Meters(float m) {
meters = m;
}
// display meters
void display() {
cout << meters << " meters" << endl;
}
};
int main() {
Feet f(10);
Meters m = static_cast<float>(f); // convert Feet to Meters using conversion operator
cout << "Feet: ";
f.display();
cout << "Meters: ";
m.display();
return 0;
}
This program defines two classes Feet
and Meters
. Feet
has a private member variable feet
and a constructor to initialize it. Meters
has a private member variable meters
and a constructor to initialize it. Feet
also has a conversion operator that converts a Feet
object to a float
representing the equivalent value in meters.
In the main()
function, a Feet
object is created with a value of 10. A Meters
object is also created and initialized with the value of the Feet
object using a static_cast
to convert the Feet
object to a float
using the conversion operator.
The display()
member functions are called on both objects to display their values in feet and meters, respectively.
The output will be the value of the Feet
object in feet and the equivalent value of the Meters
object in meters.