这章我们来看一看单双目运算符重载的区别
一、双目运算符双目运算符有两个操作数,通常在运算符的左右两侧,如:“+”、“-”、“=”、“<”等
下面设计一个月日加减的运算符重载
#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;}这里是作为友元函数进行双目运算符重载的,当然也可以作为成员函数,若不是很明白可以看上一章
双目运算符整体还是比较简单的,我们不做多说,下面来看看单目运算符的重载
?
二、单目运算符重载单目运算符只有一个操作数,如:“!”、“-”、“++”、“--”、“&”、“*”等
单目运算符重载还是按刚才的例子
#include <iostream>using namespace std;class Date{private:int year;int month;int day;public:Date();Date(int , int ,int);Date operator ++ (int); //单目运算符重载函数声明 friend Date operator + (Date &, Date &); void display();};Date::Date(){year = 0;month = 0;day = 0;}Date::Date(int 香港vps 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;}Date Date::operator ++ (int) //单目运算符重载函数 {day++;if(day >= 30){day -= 30;month++;}return *this; //返回本身类 }void Date::display(){cout << year << "-" << month << "-" << day << endl;} int main(){Date c(2000, 0, 0), s(19, 2, 4), n;n = c + s;n++;n.display();return 0;}这里单目运算符重载函数作为成员函数,省略了参数
这里以运算符“++”为例,有一个问题
“++”、“--”运算符有两种使用方式,前置自增运算符和后置自增运算符,怎么区分这两者呢?
上面代码是后置自增方式,在自增(自减)运算符函数中,增加一个int型形参
前置运算符写法只需要一点小小变动
将声明和函数中int给删去,并运用前置自增运算符
Date operator ++ ();//类中声明...Date Date::operator ++ () //单目运算符重载函数{day++;if(day >= 30){day -= 30;month++;}return *this;}...++n; //主函数中调用前置自增运算符?
03481034