Question

I have the following equals operator:

  bool operator==(const Duration& x, const Duration& y){
        return ( x.hrs == y.hrs, x.mins == y.mins, x.secs == y.secs );
    }

I have also tried:

 bool operator==(const Duration& x, const Duration& y){
        return ( (x.hrs == y.hrs) && (x.mins == y.mins) && (x.secs == y.secs) );
    }

In my main method I have:

  //Arbitrary Durations - Testing
    Duration dTest0 (01,45,12);
    Duration dTest1 (01,35,45);
    Duration dTest2 (01,35,45);
    Duration dTest3 (01,25,05);

    if ( dTest0 == dTest1 ){
        cout<< "broken" << endl;
    }
    else{
        cout<< "working" << endl;
        }

My program keeps outputting "broken" which suggests that dTest0 and dTest1 are infact equal... Where am I going wrong?

Additional: If I use x.getHours == y.getHours... It puts a red line under the "." and says: 'Error: a pointer to a bound function may only be used to call the function`.

Any advice would be appreciated. Thanks.

Was it helpful?

Solution

The first implementation will only return true if x.secs == y.secs. The results of the first two comparisons will be discarded. The , operator evaluates to the value of its second operand, which in this case boils down to just x.secs == y.secs.

The second one, however, is correct. If it is not working, then you must be setting the values of hrs, mins, and secs incorrectly in the constructor of Duration.

The problem that you have with getHours is that you need to call it. It is a member function after all. So do x.getHours() instead of x.getHours.

OTHER TIPS

The first one is wrong. , does not work that way.

The second one is correct, assuming Duration is reasonable.

You may have a bug in your Duration constructor. I'd even think it is likely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top