Lor*_*lli 6 c++ operator-overloading unary-operator
我正在尝试运算符重载,发现了一些我无法解释的东西:
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;
};
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
输出是
Unary+ called
3
Unary+ called
4
Unary+ called
4
Binary+ called
1
Run Code Online (Sandbox Code Playgroud)
为什么+(a,b)被评估为一元运算符+ b?我没有解释这一点.
链接到相关的线程运算符重载.我正在使用VisualStudio 2012.
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |