I'm self learning C++ from a book (Schaums Programming with c++) and i've come across something i want to try but it doesn't cover(as fair as i can tell).
I have a class that contains hrs
:mins
:secs
.
Is it possible to write a type conversion that will return the Object in form of a total as an integer?
If not that may be why i can not find anything. Thanks.
Sure, you just have to write a cast operator. Assuming you want to convert your time to seconds:
class MyTime
{
...
public:
operator int() const
{
return hours_ * 3600 + minutes_ * 60 + seconds_;
}
}
In C++11 you can also add the keyword explicit
to your operator so that your cast will explicitly require a static_cast<int>
in order to compile.
Assuming this is a time duration with a resolution of seconds, then yes -- something like hours * 3600 + minutes * 60 + seconds
should give you an integer number of seconds in the duration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With