I am experimenting with operator overloading and found something that I cannot explain:
WeekDays.h
using namespace std; enum DAYS { MON, TUE, WED, THU, FRY, SAT, SUN }; DAYS operator+(DAYS&a,DAYS &b) { printf("Binary+ called\n"); return (DAYS)(((unsigned int)a+(unsigned int)b)%7); } //Increment 3 DAYS operator+(DAYS&a) { printf("Unary+ called\n"); return (DAYS)(((unsigned int)a+3)%7); } ostream& operator<<(ostream&o, DAYS &a) { switch(a){ case MON: o<<"MON"; break; case TUE: o<<"TUE"; break; case WED: o<<"WED"; break; case THU: o<<"THU"; break; case FRY: o<<"FRY"; break; case SAT: o<<"SAT"; break; case SUN: o<<"SUN"; break; } return o; };
main.cpp
#include <iostream>
Output
Unary+ called 3 Unary+ called 4 Unary+ called 4 Binary+ called 1
Why is + (a, b) evaluated as a unary operator + b? I could not explain it.
Link to the relevant topic Operator overload . I am using VisualStudio 2012.
source share