C++ ——赋值运算符重载函数


前言

在介绍赋值运算符重载之前,我们先看一段代码:

class Complex    //定义一个复数类
{
public:
    Complex (double r = 0.0,double i = 0.0) //构造函数
    {
        _real = r;
        _imag = i;
    }
    void Show()const;
private:
    double _real,_imag;
};
int main()
{
    //声明2个对象
    Complex a(10,20);
    Complex b (20,30);
    return 0;
}

此时,如果我们需要对a和b进行加法运算该咋整?一般情况下我们自然都能想到使用" + “运算符,写出一个表达式:” a + b",但是很遗憾,编译的时候必会报错,因为编译器不知道该怎么处理这个加法,这个时候就需要我们自己来编写作用在Complex类对象的"+"功能,这便引出了运算符重载

一、赋值运算符重载函数是什么?

赋值运算符重载是对已经有的运算符赋予多重含义,使同一个运算符作用于不同类型的数据时有着不同的含义。

函数名为:关键字operator后面加上需要重载的运算符符号

函数原型:

返回值类型 operator 运算符 (形参列表)
{
    //函数体
}

Notes:运算符重载的实质就是函数的重载:在实现的过程中,首先把指定的运算表达式转化为对运算符的调用,将运算对象转化为运算符函数的参数,然后根据参数的类型来确定需要调用的函数。

二、细谈赋值运算符重载函数

2.1 参数列表

一般情况下,赋值运算符重载函数的参数是函数所在类的const类型的引用,加const的引用原因如下:

  1. 程序员不希望在函数中对已经用const修饰的值做任何修改。
  2. 加上const后,对于const和非const的参数,函数就能接受;如果不加,就只能接受非const的参数。

加引用的原因:

加上引用后可以有效的避免函数调用时对实参的拷贝,提高了程序的效率。

Notes:以上的规定不是强制性规定。可以不加const,也可以没有引用,甚至参数可以不是函数所在的对象。

2.2 返回值

一般情况下,返回值是被赋值者的引用,即*this,原因如下:

  1. 返回*this,避免了函数的一次拷贝,提高程序效率。
  2. 返回引用还可以达到连续赋值的作用,比如"a = b = c"。如果返回类型不是引用而是返回值类型,那么在执行b = c 时候,调用赋值运算符重载函数,在函数返回的时候,会形成一个无名的临时对象,接着拷贝临时对象,然后将这个临时对象返回,但是这临时对象是一个右值,再进行a = 时候,会出错。

2.3调用时机

当为一个类对象赋值时,会由该对象调用该类的赋值运算符重载函数。

    MyStr str1;
    str1 = str2;
    MyStr str3 = str2;

比如上述例子,定义个MyStr的类。第二个语句和第三个语句在调用函数上面是有区别的。

MyStr str1;是str1的声明加定义,调用无参数的构造函数,所以str2 = str1时在str1已经存在的情况下用str2来为str1赋值,调用赋值运算符重载函数;而MyStr str3 = str2;调用的是拷贝构造函数。

二、赋值运算符重载函数练习

定义一个日期类,实现各种运算符重载:

#include <iostream>
#include <assert.h>
using namespace std;

class Date
{
    friend ostream& operator<<(ostream& out,Date &d);
    friend istream& operator>>(istream& is,Date &d);
public:
    //构造
    explicit Date (int year = 1900,int month = 1,int day = 1)
    {
        //判断参数是否合法
        if ((year >= 1900) && (month >= 1) && (day >= 1))
        {
            _year = year,_month = month,_day = day;
        }else{
            cout<<"日期非法"<<endl;
            _year = 1900,_month =  1,_day = 1;
        }
    }
    //拷贝构造
    Date (const Date &d)
    {
        _year = d._year,_month = d._month,_day = d._day;
    }
    //赋值重载函数
    Date& operator=(const Date &d);
    bool operator==(const Date &d);
    bool operator!=(const Date &d);
    bool operator>(const Date &d);
    bool operator>=(const Date &d);
    bool operator<(const Date &d);
    bool operator<=(const Date &d);
    Date operator+(int day);
    Date& operator+=(int day);
    Date operator-(int day);
    int  operator-(const Date &d);
    Date& operator-=(int day);
    Date& operator++();
    Date operator++(int);
    Date& operator--();
    Date operator--(int);

    //析构
    ~Date() = default;

public:
    //得到某年当前月的天数
    int GetDayOfMonth(int year,int month)
    {
        assert(month > 0 && month <= 12);
        int Month_arr[13] = {0,31,29,31,30,31,30,31,31,30,31,30,31};
        int day;
        //如果不是闰年并且不是2月
        if (!(IsLeapYear()) && month == 2)
            day = Month_arr[month] - 1;
        day = Month_arr[month];
        return day;
    }

    //判断是不是闰年
    bool IsLeapYear()
    {
        return (_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0);
    }
private:
    int _year,_month,_day;
};

ostream& operator<<(ostream& out,Date &d)
{
    out<<d._year<<"-"<<d._month<<"-"<<d._day<<endl;
    return out;
}

istream& operator>>(istream& is,Date &d)
{
    cout<<"请输入日期:";
    is >>d._year;
    is >>d._month;
    is >>d._day;
    return is;

}

Date& Date::operator=(const Date &d)
{
    if (*this != d)
    {
        _year = d._year,_month = d._month,_day = d._day;
    }
    return *this;
}

bool Date::operator==(const Date &d)
{
    return (_year == d._year) && (_month == d._month) && (_day == d._day);
}

bool Date::operator!=(const Date &d)
{
    return !(*this == d);
}

bool Date::operator>(const Date &d)
{
    return (_year > d._year) || ((_year == d._year) && (_month > d._month)) || ((_year == d._year) && (_month == d._month) && (_day > d._day));
}

bool Date::operator>=(const Date &d)
{
    return (*this == d) || (*this > d);
}

bool Date::operator<(const Date &d)
{
    return (_year < d._year) || ((_year == d._year) && (_month < d._month)) || ((_year == d._year) && (_month == d._month) && (_day < d._day));
}

bool Date::operator<=(const Date &d)
{
    return (*this == d) || (*this < d);
}

Date& Date::operator++()
{
    *this = *this + 1;
    return *this;
}

Date Date::operator++(int)
{
    Date tmp = *this;
    *this += 1;
    return tmp;
}

Date& Date::operator--()
{
    *this -= 1;
    return *this;
}

Date Date::operator--(int)
{
    Date tmp = *this;
    *this -= 1;
    return tmp;
}

Date Date::operator+(int day)
{
    Date tmp = *this;
    if (day < 0)
    {
        return tmp - (-day);
    }
    tmp._day = tmp._day + day;
    while (tmp._day > GetDayOfMonth(tmp._year,tmp._month))
    {
        tmp._day = tmp._day - GetDayOfMonth(tmp._year,tmp._month);
        if (tmp._month == 12)
        {
            tmp._year++;
            tmp._month = 1;
        }else{
            tmp._month++;
        }
    }
    return tmp;
}

Date& Date::operator+=(int day)
{
    *this = *this + day;
    return *this;
}

Date Date::operator-(int day)
{
    Date tmp = *this;
    if (day < 0)
    {
        return tmp + (-day);
    }
    tmp._day = tmp._day - day;
    while (tmp._day <= 0)
    {
        if (tmp._month == 1)
        {
            tmp._year--;
            tmp._month = 12;
        }else{
            tmp._month = tmp._month - 1;
        }
        tmp._day = tmp._day + GetDayOfMonth(tmp._year,tmp._month);
    }
    return tmp;
}

Date& Date::operator-=(int day)
{
    *this = *this - day;
    return *this;
}

int Date::operator-(const Date &d)
{
    Date Max = *this;
    Date Min = d;
    int flag = 1;
    if (*this < d)
    {
        Min = *this;
        Max = d;
        flag = -1;
    }
    int day = 0;
    while (Max != Min)
    {
        --Max;
        ++day;
    }
    return flag * day;
}

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值