我正在尝试运算符重载,发现了一些我无法解释的东西:
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(); }
输出是
Unary+ called 3 Unary+ called 4 Unary+ called 4 Binary+ called 1
为什么(a,b)被评估为一元运算符b?我没有解释这一点.
链接到相关主题Operator overloading.
我正在使用VisualStudio 2012.
解决方法
使用(a,b),您恰好调用奇数
“comma” operator,首先计算a,然后计算b,最后返回b.
您可以通过将其拼写为运算符(a,b)来调用运算符. (这里的逗号是参数的分隔符,而不是逗号运算符).