Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class converting Object to Integer

Tags:

c++

integer

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.

like image 778
binary101 Avatar asked Dec 05 '12 18:12

binary101


Video Answer


2 Answers

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.

like image 196
user703016 Avatar answered Sep 19 '22 23:09

user703016


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.

like image 40
Jerry Coffin Avatar answered Sep 20 '22 23:09

Jerry Coffin