I don’t know if this question is already answered on stackoverflow. But I simply can not find the right keyword to search for.
I inserted some stripped down version of my code below.
So basically what I’m trying to do in my main(), is to subtract 122 from t2. I suppose my compiler converts the integer to a Timestamp object automatically and then subtracts it as showed in ‘Timestamp.cpp’.
But when it arrives at t4 it doesn’t convert it and give me the following error:
no match for ‘operator-‘ in ‘722 – t1’
I’m 100% sure that it is possible. But how?
Maybe I’m totally wrong about converting… So please do hesitate to correct me, I’m trying to learn something.
STRIPPED DOWN CODE:
main.cpp:
#include <iostream>
#include <iomanip>
#include "Timestamp.h"
using namespace std;
int main() {
Timestamp t3(t2 - 122);
cout << "T3 = " << t3 << endl;
Timestamp t4(722 - t1);
cout << "T4 = " << t4 << endl;
return 0;
}
Timestamp.h
#ifndef TIJDSDUUR_H
#define TIJDSDUUR_H
using namespace std;
class Timestamp {
public:
Timestamp(int);
Timestamp operator- (const Timestamp &t);
private:
int hour;
int min;
};
Timestamp.cpp
Timestamp::Timestamp(int m) : hour(0), min(m) {
}
Timestamp Timestamp::operator- (const Timestamp &t) {
Timestamp temp;
temp.hour = hour;
temp.min = min;
temp.hour -= t.hour;
temp.min -= t.min;
while(temp.min < 0.00) {
temp.hour--;
temp.min += 60;
}
return temp;
}
Contrary to what the other answers propose, you do not need to provide an specialized
operator-that takes anintand aTimestamp, rather you can (and probably should) makeoperator-a non-member function:That way the compiler is free to apply conversions to both the left hand side and the right hand side operands, and use the implicit conversion from
inttoTimestamp.You can read a short description on design and implementation of operator overloads here, or you can search in the [C++-faq] tag in SO for “operator overload”.