In operator overloading, the following types of type conversion are possible:
- Basic type conversion - This involves conversion of one basic data type to another. For example, converting an integer to a float.
- Class type conversion - This involves conversion of an object of one class type to an object of another class type.
Here is an example program showing the basic class type conversion:
using namespace std;
class Distance {
private:
int feet;
int inches;
public:
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
operator int() {
return feet;
}
};
int main() {
Distance d1(10, 6);
int feet;
feet = d1;
cout << "Feet : " << feet << endl;
return 0;
}
In the above program, a class named Distance is defined with two private data members feet and inches. The class also has two constructors, one with no arguments and another with two integer arguments to initialize the data members. The class also has a conversion operator of type int, which converts an object of type Distance to an integer, by returning the value of feet.
In the main function, an object d1 of type Distance is created and initialized to 10 feet and 6 inches. The object is then assigned to an integer variable feet using the conversion operator, and the value of feet is printed.
No comments:
Post a Comment
If you have any doubts, please let me know