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
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- [C++]运算符重载
- 【c++】运算符重载
- C++:运算符重载
- C#:运算符重载
- C++:运算符重载
- poj 3723 Conscription
- 机器学习资源(网址)
- 简单实现FTP下载
- Java中的==和equals区别
- Color the ball
- C++ 重载运算符
- 学习笔记_毕向东 Java_继承_抽象类_接口_多态 2014.7.13
- ubuntu设置声音大小
- 高精度小数相加
- Qt学习(八) 关于托盘菜单不消失的问题
- Ubuntu14.04LTS下使用eclipse搭建Cocos2d-x的Android环境
- 关于友善之臂mini2440串口接超级终端输入显示乱码问题的解决方法
- 中缀表达式转后缀表达式
- 【环境配置】Linux的常用命令