这章我们来看一看单双目运算符重载的区别
一、双目运算符
双目运算符有两个操作数,通常在运算符的左右两侧,如:“+”、“-”、“=”、“<”等
下面设计一个月日加减的运算符重载
#include <iostream>
using namespace std;
class Date
{
private:
int year;
int month;
int day;
public:
Date();
Date(int , int ,int);
friend Date operator + (Date &, Date &); //运算符重载作为友元函数
void display();
};
Date::Date()
{
year = 0;
month = 0;
day = 0;
}
Date::Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
Date operator + (Date &c1, Date &c2) //双目运算符重载
{
Date c;
c.year = c1.year + c2.year;
c.month = c1.month + c2.month;
c.day = c1.day + c2.day;
return c;
}
void Date::display()
{
cout << year << "-" << month << "-" << day << endl;
}
int main()
{
Date c(2000, 0, 0), s(19, 2, 4), n;
n = c + s;
n.display();
return 0;
}