C++赋值运算符重载

运算符重载
 

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数
函数名字:关键字operator后面接需要重载的运算符符号
函数模型:返回值类型 operator操作符(参数列表)

注意事项:

1 不能通过连接其他符号来创建新的操作符:比如operator@
2 重载操作符必须有一个类类型参数
3 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义,让它有符号-的功能
4 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐
藏的this

5 .*   ::   sizeof   ?:    .  这5个运算符不可重载

赋值运算符重载
 

赋值运算符只能重载成类的成员函数不能重载成全局函数
 

原因:赋值运算符如果不显式实现,编译器会生成一个默认的。若我们再在类外自己实现
一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了

用户没有显式实现时,编译器会生成一个默认赋值运算符重载

对内置类型成员:值拷贝(浅拷贝)

对自定义类型成员:调用它的赋值运算符重载

 那么再来回顾以下以往的默认成员函数吧:

默认构造函数和默认析构函数:

1 对于内置类型成员:不做处理

2 对于自定义类型成员:调用它的默认构造函数和析构函数

默认拷贝构造函数和默认赋值重载函数:

1 对于内置类型成员:值拷贝(浅拷贝)

2 对于自定义类型成员:调用它的拷贝构造函数和赋值重载函数

拷贝构造和赋值重载的区别:

拷贝构造是用一个已存在的对象去初始化地创建一个新对象

赋值重载是两个已存在对象之间的拷贝

若类中未涉及到资源管理(堆上申请空间),赋值运算符是否实现都可以(编译器默认生成的赋值重载函数足够了),一旦涉及到资源管理则必须要实现
在以下示例中,我没有写赋值重载函数,只有编译器默认生成的,那么会对内置类型成员完成值拷贝,栈是申请空间的,以下程序就崩溃了

//以下程序崩溃
typedef int DataType;
class Stack
{
public:
	Stack(size_t capacity = 10)
	{
		_a = (DataType*)malloc(sizeof(DataType) * capacity);
		if (nullptr == _a)
		{
			perror("malloc fail");
			exit(-1);
		}
		_size = 0;
		_capacity = capacity;
	}

	~Stack()
	{
		free(_a);
		_a = nullptr;
		_size = _capacity = 0;
	}

	void Push(const DataType& data)
	{
		//CheckCapacity…… 扩容
		_a[_size++] = data;
	}
private:
	DataType* _a;
	size_t _size;
	size_t _capacity;
};

int main()
{
	Stack s1;
	s1.Push(1);
	s1.Push(2);
	s1.Push(3);
	s1.Push(4);

	Stack s2;
	s2 = s1;//赋值
}

原因:

所以以上这种有申请资源的情况若是对象之间需要赋值,那么我们就必须自己写,完成深拷贝

const成员
 

const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数
隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改
 

this指针不能在实参和形参的位置进行直接显示,所以用const修饰this指针的用法比较特殊

一些细节:权限可以缩小、平移 但不能放大

 1. const对象不可以调用非const成员函数

     这样是权限的放大,const对象不可修改,但是调用非const成员函数的对象是可以修改的


 2. 非const对象可以调用const成员函数

      这样是权限的缩小,非const对象可以修改,调用const成员函数的对象是不可修改的,权限可以缩小


 3. const成员函数内不可以调用其它的非const成员函数

     这样是权限的放大,const成员函数的this指针指向的是不可修改的对象,非const成员函数的this指针指向的是可修改的对象,const成员函数若是调用非const成员函数,传递this指针,则让不可修改的对象变成了可以修改,是不行的


 4. 非const成员函数内可以调用其它的const成员函数

     这样是权限的缩小,非const成员函数的this指针指向的是可修改的对象,const成员函数的this指针指向的是不可修改的对象,非const成员函数调用const成员函数,传递this指针,让可修改的对象变成了不可修改的对象,是ok的

下面我以日期类来演示相关运算符重载的代码实现:

运算符重载的代码实现

下面我会将声明和定义分开,声明在.h头文件中,定义在.cpp中

Date.h:

#include<iostream>
using namespace std;

class Date
{
	friend ostream& operator<<(ostream& out, const Date& d);//友元函数的声明
	friend istream& operator>>(istream& in, Date& d);
public:
	int GetMonthDay(int year, int month)const;//获取对象的成员月份所对应的天数
	Date(int year = 1, int month = 1, int day = 1);//构造函数(初始化功能)
	void Print()const;

	Date& operator=(const Date& d);//赋值重载函数 其实没必要写,编译器默认生成的会完成值拷贝够用了
	bool operator<(const Date& d)const;//<运算符重载函数
	bool operator==(const Date& d)const;//==运算符重载函数
	bool operator<=(const Date& d)const;//<=运算符重载函数
	bool operator>(const Date& d)const;//>运算符重载函数
	bool operator>=(const Date& d)const;//>=运算符重载函数
	bool operator!=(const Date& d)const;//!=运算符重载函数

	Date& operator++();//前置++运算符重载函数
	Date operator++(int);//后置++运算符重载函数
	Date& operator--();//前置--运算符重载函数
	Date operator--(int);//后置--运算符重载函数

	Date& operator+=(int day);//+=运算符重载函数
	Date operator+(int day)const;//+运算符重载函数
	Date& operator-=(int day);//-=运算符重载函数
	Date operator-(int day)const;//-运算符重载函数

	int operator-(const Date& d)const;//-运算符重载函数(日期类对象相减求相差天数)
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"

int Date::GetMonthDay(int year, int month)const//获取某年某月的天数
{
	static int monthDay[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	if (month == 2
		&& ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))//闰年且是2月
	{
		return 29;
	}
	return monthDay[month];
}


Date::Date(int year, int month , int day )//声明给缺省值定义不给 全缺省的构造函数
{
	_year = year;
	_month = month;
	_day = day;
	
	if (month < 1 || month>12
		|| day<1 || day>GetMonthDay(year, month))
	{
		cout << "非法日期" << endl;
	}
}

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

Date& Date::operator=(const Date& d)//赋值运算符重载,两日期类对象间的赋值
{
	if (this != &d)//自己就不用给自己赋值了,如d1=d1
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	return *this;//连续赋值,需要返回*this  如d3=d2=d1(从右边先开始赋值,d2=d1后返回d2,再执行d3=d2
}

bool Date::operator<(const Date& d)const//<运算符重载
{
	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;
	}
	else
	{
		return false;
	}

}

bool Date::operator==(const Date& d)const//==运算符重载
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator<=(const Date& d)const//<=运算符重载
{
	return *this < d || *this == d;
}

bool Date::operator>(const Date& d)const//>运算符重载
{
	return !(*this <= d);
}

bool Date::operator>=(const Date& d)const//>=运算符重载
{
	return !(*this < d);
}

bool Date::operator!=(const Date& d)const//!=运算符重载
{
	return !(*this == d);
}

Date& Date::operator++()//前置++
{
	*this += 1;
	return *this;//this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
}

Date Date::operator++(int)//后置++,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;//temp是临时对象,因此只能以值的方式返回,不能返回引用
}

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)const//日期+天数
{
	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)
		{
			--_year;
			_month = 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

Date Date::operator-(int day)const//日期-天数
{
	Date tmp(*this);
	tmp -= day;
	return tmp;
}

int Date::operator-(const Date& d)const//日期-日期 返回天数
{
	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;
}

ostream& operator<<(ostream& out, const Date& d)//流插入运算符重载
{
	out << d._year << "/" << d._month << "/" << d._day << endl;
	return out;
}

istream& operator>>(istream& in, Date& d)//流提取运算符重载
{
	in >> d._year >> d._month >> d._day;
	return in;
}

细谈一些运算符重载的代码

 

 

 

< 、==、<=、>、>=、!=运算符的重载

只需要写出<、==或者>、==两种组合种的任意一种组合即可,其他运算符可以直接复用

若是不用友元想得到私有成员的值或者修改私有成员,可以在类中写函数来实现目的

这里函数的声明和定义是分开的

	//date.h中
//类中声明
    int GetY()const;//获取年
	int GetM()const;//获取月
	int GetD()const;//获取天

	int& Year();//得到私有成员的别名
	int& Month();
	int& Day();

 

//Date.cpp中
int Date::GetY()const
{
	return _year;
}

int Date::GetM()const
{
	return _month;
}

int Date::GetD()const
{
	return _day;
}

int& Date::Year()
{
	return _year;
}

int& Date::Month()
{
	return _month;
}

int& Date::Day()
{
	return _day;
}
ostream& operator<<(ostream& out, const Date& d)
{
	//out << d._year << "/" << d._month << "/" << d._day << endl;//用了友元
	out <<d.GetY() << "/" << d.GetM() << "/" << d.GetD() << endl;//不用友元

	return out;
}

istream& operator>>(istream& in, Date& d)
{
	//in >> d._year >> d._month >> d._day;//用了友元
	in >> d.Year() >> d.Month() >> d.Day();//不用友元
	return in;
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值