类和对象(3)

赋值运算符重载

运算符重载

  • 当运算符被用于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错
  • 运算符重载是具有特殊名字的函数,他的名字是由operator和后面要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。
  • 重载运算符函数的参数个数和该运算符作用的运算对象数量⼀样多。⼀元运算符有⼀个参数,⼆元运算符有两个参数,⼆元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第⼆个参数。
#include<iostream>

using namespace std;

// 编译报错:“operator + ”必须至少有一个类类型的形参
int operator+(int x, int y)
{
	return x - y;
}

class A
{
public:
	void func()
	{
		cout << "A::func()" << endl;
	}
};

typedef void(A::* PF)(); //成员函数指针类型

int main()
{
	// C++规定成员函数要加&才能取到函数指针
	PF pf = &A::func;

	A obj;

	//对象调用成员函数指针时,使用.*运算符
	(obj.*pf)();
	return 0;
}
  • 如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数比运算对象少⼀个
  • 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持一致
  • 不能通过连接语法中没有的符号来创建新的操作符:比如operator@
  • .* :: sizeof ?: .注意以上5个运算符不能重载
  • 重载操作符至少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如:int operator+(int x, int y)
  • 一个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator-就有意义,但是重载operator+就没有意义。
#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
//private:
	int _year;
	int _month;
	int _day;
};

// 重载为全局的面临对象访问私有成员变量的问题
// 有几种方法可以解决:
// 1、成员放公有
// 2、Date提供getxxx函数
// 3、友元函数
// 4、重载为成员函数
bool operator==(const Date& d1, const Date& d2)
{
	return d1._year == d2._year
		&& d1._month == d2._month
		&& d1._day == d2._day;
}

int main()
{
	Date d1(2024, 7, 5);
	Date d2(2024, 7, 6);

	operator==(d1, d2);
	// 编译器会转换成operator==(d1, d2);
	d1 == d2;
	return 0;
}
  • 重载++运算符时,有前置++后置++,运算符重载函数名为operator++,无法很好的区分。C++规定,后置++重载时,增加一个int形参,跟前置++构成函数重载,方便区分
#include<iostream>
using namespace std;

class Date
{
public:
    Date(int year = 1, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }

    void Print()
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }

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

    Date& operator++()
    {
        cout << "前置++" << endl;
            //...
        return *this;
    }

    Date operator++(int)
    {
        Date tmp;
        cout << "后置++" << endl;
            //...
        return tmp;
    }
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    Date d1(2024, 7, 5);
    Date d2(2024, 7, 6);
 
    d1.operator==(d2);
    d1.operator==(d2);
    d1 == d2;
    d1.operator++();
    ++d1;
    // 编译器会转换成d1.operator++(0);
    d1++;
    return 0;
}
  • 重载<<>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调用时就变成了对象<<cout,不符合使用习惯和可读性。重载为全局函数把ostream/istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对象。

赋值运算符重载

赋值运算符重载是⼀个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意跟拷贝构造区分,拷贝构造用于一个对象拷贝初始化给另一个要创建的对象

赋值运算符重载的特点:

  • 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成const 当前类类型引用,否则会传值传参会有拷贝。
  • 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了支持连续赋值场景。
  • 没有显式实现时,编译器会自动生成⼀个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对自定义类型成员变量会调用他的赋值重载函数
  • Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动⽣成的赋值运算符重载就可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的赋值运算符重载会调用Stack的赋值运算符重载,也不需要我们显示实现MyQueue的赋值运算符重载。这⾥还有⼀个小技巧,如果⼀个类显示实现了析构并释放资源,那么他就需要显示写赋值运算符重载,否则就不需要。
#include<iostream>
using namespace std;

class Date
{
public:
    Date(int year = 1, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    Date(const Date& d)
    {
        cout << " Date(const Date& d)" << endl;
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
    // 传引用返回减少拷⻉

    // d1 = d2;
    Date& operator=(const Date& d)
    {
    //要检查自己给自己赋值的情况
        if (this != &d)
        {
            _year = d._year;
            _month = d._month;
            _day = d._day;
        }
        // d1 = d2表达式的返回对象应该为d1,也就是* this
        return *this;
    }
    void Print()
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }
private:
    int _year;
    int _month;
    int _day;
};

int main()
{
    Date d1(2024, 7, 5);
    Date d2(d1);
    Date d3(2024, 7, 6);
    d1 = d3;
    //需要注意这里是拷⻉构造,不是赋值重载
    //请牢牢记住赋值重载完成两个已经存在的对象直接的拷⻉赋值
    //而拷⻉构造用于⼀个对象拷⻉初始化给另⼀个要创建的对象

    Date d4 = d1;
    return 0;
}

日期类实现

日期类的实现分为三个文件:Date.hDate.cpptest.cpp

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

class Date
{
	//友元函数声明
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	//全缺省函数声明
	Date(int year = 1900, int month = 1, int day = 1);
	//打印
	void Print();
	//获得每月的天数(注意闰年)
	int GetMonthDay(int year, int month)
	{
		assert(month >0 || month < 13);
		static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
		//将month写在前面可以加快计算机的运行速度,当月份不为2时,
		//后面的润年判断会直接被短路
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) 
		|| year % 400 == 0))
		{
			return 29;
		}
		return monthDayArray[month];
	}

	bool CheckDate()
	{
		if (_month < 1 || _month > 12 || _day < 1 
		|| _day > GetMonthDay(_year,_month))
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//日期比较
	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);
	Date operator-(int day);

	// ++d1
	Date& operator++();
	// d1++
	Date operator++(int);

	// --d1
	Date& operator--();
	// d1--
	Date operator--(int);

	int operator-(const Date& d);

private:
	int _year;
	int _month;
	int _day;
};
//日期输入输出
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);
  • Date.cpp
#include"Date.h"

Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
	if (!CheckDate())
	{
		cout << "非法日期—>" ;
		cout << *this;
	}
}

void Date::Print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}

日期比较大小(只需写两个,便可实现其他的)

bool Date::operator<(const Date& d)
{
	if (_year < d._year)
	{
		return true;
	}
	else if (_year == d._year && _month < d._month)
	{
		return true;
	}
	else if (_year == d._year && _month == d._month && _day < d._day)
	{
		return true;
	}
	return false;
}

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

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

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

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);
}

日期加减

思路:

  1. 先将_day进行加减
  2. 通过_day将日期进行调整
Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		return *this -= -day;
	}
	_day += day;
	while (_day > GetMonthDay(_year,_month))
	{
		_month++;
		_day -= GetMonthDay(_year, _month);
		if (_month > 12)
		{
			_month = 1;
			_year++;
		}
	}
	return *this;
}

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

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;
	}
	_day -= day;
	while (_day < 0)
	{
		_month--;
		_day += GetMonthDay(_year, _month);
		if (_month == 0)
		{
			_month = 12;
			_year--;
		}
	}
	return  *this;
}

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

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

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

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

// d1--
Date Date::operator--(int)
{
	Date tmp = *this;
	*this -= 1;
	return tmp;
}
//注意有正负
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}
	int n = 0;
	while (max != min)
	{
		min++;
		n++;
	}
	return n*flag;
}

日期的输入输出
思路:

  1. 由于this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调用时就变成了对象<<cout,不符合使用习惯和可读性。
  2. 重载为全局函数把ostream/istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对象。
ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "-" << d._month << "-" << d._day << endl;
	return out;
}

istream& operator>>(istream& in, Date& d)
{
	while (1)
	{
		cout << "请输入日期:>";
		in >> d._year >> d._month >> d._day;
		if (d.CheckDate())
		{
			break;
		}
		else
		{
			cout << "请输入正确的日期:>"<<endl;
		}
	}
	return in;
}
  • test.cpp
#include"Date.h"

int main()
{
	Date d1(2024, 8, 14);
	d1.Print();

	Date d2= d1 + 100;
	d2.Print();
	d1 += 100;
	d1.Print();

	Date d3 = d2 - 100;
	d3.Print();
	d3 -= 100;
	d3.Print();

	d3++;
	d3.Print();
	++d3;
	d3.Print();
	d3--;
	d3.Print();
	--d3;
	d3.Print();
	cout<<d3.operator<(d2)<<endl;
	cout<<d3.operator>(d2)<<endl;
	cout<<d3.operator<=(d2)<<endl;
	cout<<d3.operator>=(d2)<<endl;
	cout<<d3.operator==(d2)<<endl;
	cout<<d3.operator!=(d2)<<endl;

	Date d4(2024, 8, 14);
	Date d5(2004, 2, 5);

	cout << d4 - d5 << endl;
	cout << d5 - d4 << endl;

	Date d6(2023, 2, 29);

	cout << d1;
	operator<<(cout, d1);

	cin >> d1 >> d2;
	cout << d1 << d2 << endl;


	return 0;
}

在这里插入图片描述

  • 14
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值