我與運算符重載試驗和發現的東西,我無法解釋:C++運算符重載稱爲功能
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)'是一元+? –
@LorenzoBelli圓括號改變評估順序:「+(a,b)」首先評估圓括號的內容,然後評估一元的「+」,而+ a,b首先評估「+ a」,然後是逗號,然後是b 。 –