Reputation: 73
here is the operator function(inSeconds is of type int)
const Time Time::operator +( const Time& t) const {
return Time(inSeconds_ + t.inSeconds_);
}
but i need to also make this code work with this operator. (t1 being an instance of time and 12 being an integer) without swapping the values in the the order)
Time t(12 + t1);
please help me, sorry if this made no sense im a newbie.
thanks
Upvotes: 0
Views: 56
Reputation: 206567
Time
that takes an int
(representing seconds) as an argument.The following code works for me:
struct Time
{
Time(int sec) : inSeconds_(sec) {}
int inSeconds_;
};
Time operator+(Time const& lhs, Time const& rhs)
{
return Time(lhs.inSeconds_ + rhs.inSeconds_);
}
int main()
{
Time t1(10);
Time t2(12 + t1);
}
Upvotes: 1
Reputation: 69864
What you need is a free function operator.
struct Time {
// ...
};
// note: outside the class
Time operator+(const Time& left, const int& right)
{
return Time( /* whatever should go here */);
}
Always prefer to write binary operators as free functions that do their work in terms of utility methods on the class - your life will be easier.
Upvotes: 0