C++入门-->类和对象(下)

前言:本章笔者主要解释常用的运算符重载,实例,友元

引入:

简单来说,就是C++作为一门面向对象的语言,为了更好的灵活性和方便,引入了运算符重载的概念,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。 函数名字为:关键字operator后面接需要重载的运算符符号。 函数原型:返回值类型 operator操作符(参数列表)

赋值重载

不显示的写,编译器会自动生成一个默认赋值重载函数,完成浅拷贝。

不能重载成全局函数,只能在类中重载。

以Data类示例:

Data& operator=(const Data& data)
	{
		_year = data._year;
		_month = data._month;
		_day = data._day;
		return *this;
	}

重载+=运算符

示例

/*private:bool _Judge_leap_years = false;*/

void cmpLeapYears()
{
	if ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0))
	{
		//是闰年
		_Judge_leap_years = true;
	}
	else _Judge_leap_years = false;
}
Data& operator+=(const int& x)
{
	//闰年
	//1.能被4整除,但是不能被100整除
	//2.能整除400
	static int cmpMonDay[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	_day += x;
	while (_day > cmpMonDay[_month])
	{
		_day -= cmpMonDay[_month];
		++_month;
		if (_month > 12)
		{
			++_year;
			cmpLeapYears();
			if (_Judge_leap_years) cmpMonDay[2] = 29;
			else cmpMonDay[2] = 28;
			_month = 1;
		}
	}
	return *this;
}

重载> <,>= ,<=, ==运算符

bool operator==(const Data& data)
{
	return _year == data._year &&
		_month == data._month &&
		_day == data._day;
}
bool operator <(const Data& data)
{
	if (_year < data._year) return true;
	else if (_year == data._year && _month < data._month) return true;
	else if (_month == data._month && _day < data._day) return true;
	else return false;
}
bool operator >=(const Data& data)
{
	return !(*this < data);
}
bool operator>(const Data& data)
{
	if (_year > data._year) return true;
	else if (_year == data._year && _month > data._month) return true;
	else if (_month == data._month && _day > data._day) return true;
	else return false;
}
bool operator <=(const Data& data)
{
	return !(*this > data);
}

初提友元(friend)

友元函数:友元函数可以直接访问类的私有成员,它是定义在类外部的普通函数,不属于任何类,但需要在 类的内部声明,声明时需要加friend关键字。

1。友元函数可访问类的私有和保护成员,但不是类的成员函数

2.友元函数不能用const修饰 友元函数可以在类定义的任何地方声明,不受类访问限定符限制

3.一个函数可以是多个类的友元函数 友元函数的调用与普通函数的调用原理相同

2.友元类:友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。 但是友元关系是单向的,不具有交换性。

注意事项

1.不能通过连接其他符号来创建新的操作符:比如operator@

2..重载操作符必须有一个类类型参数

3.用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义

4.作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐 藏的this指针

5. (.* :: sizeof ?: .)这些操作符无法重载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值