5

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.

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It is better to make it explicit operator int() in C++11, alternatively int HashCode() or something.
@Nawaz Yeah, HashCode would be a really intuitive name for a function that returns time duration in seconds :P
@Praetorian: It is not seconds, it just happens to be seconds. there is a difference. Also, if he really wants to convert time into seconds, then he wouldn't have asked the question, as he (probably) knows that already (I guess). Also, in that case operator int() would surely not make sense.
Yes, my object is indeed a Duration hrs:mins:secs. @NolwennLeGuen Ah i see. So you don't have to pass it the object/parameters?
2

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.

Comments

0

You can write a function to convert your class to the desired integer value you want. The typecast methods can be overloaded. See here: http://www.learncpp.com/cpp-tutorial/910-overloading-typecasts/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.