C++ 重载运算符

来源:互联网 发布:家庭式音响推荐 知乎 编辑:程序博客网 时间:2024/05/22 14:49


#include <iostream>#include <string>#include <sstream> #include <memory> using namespace std;class Date{private:int day;int month;int year;string DateString;public:Date(int year, int month, int day);Date & operator++();/*重载前缀加*/ Date & operator--();/*重载前缀减*/Date operator++(int);/*重载后缀加*/ Date operator--(int);/*重载后缀减*/operator const char*(); /*重载类型转换运算符,内置的自动转换为char *,还可以有其它的类型转换运算符,如operator int*/void operator+=(const int days){this->day += days;}void operator-=(const int days){this->day -= days;}bool operator==(const Date &date){return date.day==this->day && date.month==this->month && date.year==this->year;}bool operator!=(const Date &date){return !((*this)==date);}};Date::Date(int year, int month, int day){this->year = year;this->month = month;this->day = day;}/*前缀加 先递增,然后返回当前对象的引用*/ Date & Date::operator++(){++day;return *this;}Date & Date::operator--(){--day;return *this;}/*后缀加,先复制当前对象,然后执行递增操作,再返回复制对象*/ Date Date::operator++(int){Date temp(year,month,day);day++;return temp;}Date Date::operator--(int){Date temp(year,month,day);day--;return temp;}Date::operator const char*(){ostringstream date;date<<year<<'-'<<month<<'-'<<day;DateString = date.str();return DateString.c_str();}int main(){Date date(2012,5,1);Date date2(2012,5,25);date += 24;cout<<date<<endl;if (date == date2)cout<<"date == date2"<<endl;elsecout<<"date != date2"<<endl;/*智能指针类,在VS2012中编译通过,即支持C++11, 在Dev C++编译错误,不支持C++11*/unique_ptr<Date> m(new Date(2000,1,1));cout<<*m<<endl;return 0;}

0 0