c++中运算符的重载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013230291/article/details/82725434
  • 为什么要重载

运算符重载能够让一个运算符根据运算符两侧的类型调用不同的函数,实现多重功能,精简优化代码。

  • 重载方式
  • 返回值 operator 运算符 (形参列表)

举例:实现两个时间相减功能,利用boost中的data_time库
重载运算符减号 “-”
使用时包含头文件

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/lexical_cast.hpp>
#include <string>

类声明:

class MyClassTimePro
{
public:
    MyClassTimePro(string str_time);///str_time format : yyyy-mm-dd
    ~MyClassTimePro();

public:
    bool operator < (MyClassTimePro& o_time);
    int operator - (MyClassTimePro& o_time);

    int MonthNum();
    int DayNum();
    int YearNum();
private:

    int year;
    int month;
    int day;
};

///构造函数解析时间字符串

MyClassTimePro::MyClassTimePro(string str_time)
{
    int pos1 = str_time.find("-");
    int pos2 = str_time.rfind("-");
    year = boost::lexical_cast<int>(str_time.substr(0, pos1));
    day= boost::lexical_cast<int>(str_time.substr(pos2 + 1));
    month = boost::lexical_cast<int>(str_time.substr(pos1 + 1, pos2 - pos1 - 1));

}
  • 声明:
int operator - (MyClassTimePro& o_time);
  • 定义:
int MyClassTimePro::operator - (MyClassTimePro& o_time)
{
    boost::gregorian::date data1(year, month, day);
    boost::gregorian::date data2(o_time.year, o_time.month, o_time.day);

    boost::gregorian::date_duration durl = data1 - data2;///已对date类进行了重载,因此能用 - 实现两个对象的相减;

    return durl.days();
}

其实在上面的重载函数中,boost库已对date类进行了重载。

猜你喜欢

转载自blog.csdn.net/u013230291/article/details/82725434