C ++ operator overloading is called a function

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> #include "WeekDays.h" using namespace std; void main() { DAYS a=MON; //=0 DAYS b=TUE; //=1 cout<< +a <<endl; cout<< +b <<endl; cout<< +(a,b) <<endl; cout<< (a+b) <<endl; cin.get(); } 

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.

+6
source share
2 answers

With (a,b) you call the odd comma operator , which evaluates first a, then b, and finally returns b.

You can call your operator by writing it as operator+(a,b) . (Here, the comma is the separator for the parameters, not the comma operator).

+10
source

Please take a look at the link http://en.cppreference.com/w/cpp/language/operator_arithmetic

unary plus, aka + a

 T::operator+() const; T operator+(const T &a); 

aka a + b

 T::operator+(const T2 &b) const; TT operator+(const T &a, const T2 &b); 

With your overloaded operator + (a, b), you should get at least this warning: warning: the left operand of the comma operator is not valid [-Unimated value]

+1
source

All Articles