C++类和对象(3)

文章目录

一、赋值运算符重载

  1.1 运算符重载

  1.2 赋值运算符重载

  1.3 日期类实现

    Date.h

    Date.c++

    test.cpp


 一、赋值运算符重载

1.1 运算符重载

  • 当运算符被⽤于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使⽤运算符时,必须转换成调⽤对应运算符重载,若没有对应的运算符重载,则会编译报错。
  • 运算符重载是具有特殊名字的函数,他的名字是由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;
	}
private:
	int _year;
	int _month;
	int _day;
};

bool operator<(const Date& x1,const Date& x2)
{
	if (x1_year < x2._year)
	{
		return true;
	}
	else if (x1._year == x2._year
		&& x1._month < x2._month)
	{
		return true;
	}
	else if (x1._year == x2._year
		&& x1._month == x2._month
		&& x1._day < x2._day)
	{
		return true;
	}

	return false;
}


	int main()
{
	Date d1(2024, 8, 9);
	Date d2(2024, 8, 10);

	bool ret2 = operator<(d1, d2);
	// 转换成调用对应的运算符重载函数
	bool ret3 = d1 < d2;

	return 0;
}

但是出现了报错 ,原因就是无法访问私有成员,所以其中一个方法就是将变为日期类的成员函数

  • 如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数⽐运算对象少⼀个
#include<iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

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

private:
	int _year;
	int _month;
	int _day;
};


	int main()
{
	Date d1(2024, 8, 9);
	Date d2(2024, 8, 10);

	bool ret2 = d1.operator<(d2);
	// 转换成调用对应的运算符重载函数
	bool ret3 = d1 < d2;


	return 0;
}
  • 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。
  • 不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。
  •  .* :: sizeof ?: . 注意以上5个运算符不能重载。
  • 重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: int operator+(int x, int y)
  • ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator-就有意义,但是重载operator+就没有意义。
  • 重载++运算符时,有前置++和后置++,运算符重载函数名都是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;
		//...此处如果实现了“+=”重载的话就可以对其赋用
		//*this+=1;
		return *this;
	}
	Date operator++(int)    
	{
		Date tmp;
		cout << "后置++" << endl;
		//...
		return tmp;
	}
private:
	int _year;
	int _month;
	int _day;
};
	int main()
{
	Date d1(2024, 8, 9);

	// 编译器会转换成 d1.operator++();
	++d1;
	// 编译器会转换成 d1.operator++(0);
	d1++;

	return 0;
}
  • 重载<<和>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位 置,第⼀个形参位置是左侧运算对象,调⽤时就变成了 对象<<cout,不符合使⽤习惯和可读性。 重载为全局函数把ostream/istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对象。

此时可以使用第二种方法——友元函数声明:

#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 = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	
	//检查日期是否合理
	bool CheckDate()
	{
		if (_month < 1 || _month > 12
			|| _day < 1 || _day > GetMonthDay(_year, _month))
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	//获取月份天数
	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 };

		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			return 29;
		}

		return monthDayArray[month];
	}
	
private:
	int _year;
	int _month;
	int _day;
};

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


	int main()
{
	Date d1(2024, 8, 9);
	
	cout << d1;
	//operator<<(cout, d1);

	cin >> d2;
	cout << d2;

	return 0;
}

 1.2 赋值运算符重载

  • 赋值运算符重载是⼀个默认成员函数,⽤于完成两个已经存在的对象直接的拷⻉赋值,这⾥要注意跟拷⻉构造区分,拷⻉构造⽤于⼀个对象拷⻉初始化给另⼀个要创建的对象。
#include<iostream>
#include<assert.h>
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)
	{
		
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

	Date& operator=(const Date& d)
	{
    // 不要检查⾃⼰给⾃⼰赋值的情况
        if (this != &d)
		{
        _year = d._year;
		_month = d._month;
		_day = d._day;
        }

		return *this;
	}

private:
	int _year;
	int _month;
	int _day;
};

	int main()
{
		Date d1(2024, 8, 10);
			// 拷贝构造用于一个已经存在对象拷贝初始化给另一个要创建的对象。
			Date d2(d1);
			Date d4 = d1;
		
			// 用于完成两个已经存在的对象直接的拷贝赋值
			Date d3(2024, 9, 11);
			/*d1 = d3;*/
			//d1.operator=(d3);
			d1 = d2 = d3;
           
            return 0;
}

 总的来说:

  1. 构造函数:一般都需要自己写,自己传参和初始化函数;
  2. 析构函数:析构时有资源申请,就需要显示写析构函数;
  3. 拷贝构造和复制重载,显示写了析构,内部管理资源,就需要显示实现深拷贝;

1.3 日期类实现

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

class Date
{
	

public:
	Date(int year = 2024, 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 };

		
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			return 29;
		}

		return monthDayArray[month];
	}

	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;
};
Date.c++
#include"Date.h"

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

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 _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator>(const Date& d)
{
	//对“<=”进行赋用,
	//如果 *this <= d 返回 false就说明是“>”,在对其 ! ,此时就会 return true。 
	return !(*this <= d);
}
bool Date::operator<=(const Date& d)
{
	//同理对“<”和“==”进行赋用
	//如果 *this <= d 返回 ture 或者  *this == d 返回 ture
	return *this < d || *this == d;
}

bool Date::operator>=(const Date& d)
{
	//同理对“<”进行赋用
	//如果 *this < d 返回 false就说明是“>”,在对其 ! ,此时就会 return true。
	return !(*this < d);
}


bool Date::operator!=(const Date& d)
{
	//同理对“==”进行赋用
	//如果   *this == d 返回 false 就说明是“!=”,在对其 ! ,此时就会 return true。
	return !(*this == d);
}

Date& Date::operator+=(int day)
{
	//如果要加的天数为负数,就可以对“-=”赋用
	if (day < 0)
		return *this -= -day;

	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;
		if (_month == 13)
		{
			_year++;
			_month = 1;
		}
	}

	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;
		if (_month == 0)
		{
			_month = 12;
			--_year;
		}

		_day += GetMonthDay(_year, _month);
	}

	return *this;
}

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

	return tmp;
}

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

 // d1++
 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;
 }

 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 (min != max)
	{
		++min;
		++n;
	}

	return n * flag;
}

 

test.cpp
 

 未完待续~~

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值