|
Not only can we overload operators such as + and ++ in our own user-defined classes, we can also overload typecasting functions such float() and int() to convert our own classes into basic types (for example, for turning a custom String class into a character array). This is very similar to the other operator overloaders we have seen.
class Burrito {
private:
int amtbeef, amtbean;
public:
Burrito(int newbeef, int newbean) {
amtbeef = newbeef;
amtbean = newbean;
}
operator int() {
return (amtbeef + amtbean);
}
};
The above class contains an int() operator, which we can use similarly to any other type cast, such as:
void main(void) {
Burrito b1(10,6);
int i1 = int(b1);
cout << i1 << endl;
}
That short example would print out the number 16, and demonstrates how to use operator overloading to convert a user-defined class to a basic type. To go the other way (from a basic-type to a user defined class), you simply use a constructor, like we saw when learning about constructors. |