C++赋值运算符重载

赋值运算符重载

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类
型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

函数名字为:关键字operator后面接需要重载的运算符符号。
用于内置类型的操作符,其含义不能改变,例如:内置的整型+,不 能改变其含义
注:.* 、:: 、sizeof 、?: 、. 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。

函数原型:返回值类型 +operator+操作符+(参数列表)

例:

// 全局的operator==
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//private:
int _year;
int _month;
int _day;
};
// 这里会发现运算符重载成全局的就需要成员变量是共有的,那么问题来了,封装性如何保证?
// 这里其实可以用我们后面学习的友元解决,或者干脆重载成成员函数。
bool operator==(const Date& d1, const Date& d2) {
return d1._year == d2._year;
&& d1._month == d2._month
&& d1._day == d2._day; }
void Test ()
{
Date d1(2018, 9, 26);
Date d2(2018, 9, 27);
cout<<(d1 == d2)<<endl;
}

运算符重载例子:

class Date {
public:
	//全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1) {
		_year = year;
		_month = month;
		_day = day;
	}

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

	Date& operator++() {   //运算符重载
		_day += 1;
		return *this;
	}

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

int main() {
	int a = 10;
	a++;

	Date d1(2019, 8, 1);
	Date d2(2019, 8, 1);
	d2 = d1++;

	system("pause");
	return 0;
}

赋值运算符重载:

class Date
{
public :
Date(int year = 1900, 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;
}
}
private:
int _year ;
int _month ;
int _day ;
};

Date类运算符重载案例

//完善的Date类
class Date {
public:
	Date(int year = 1900, int month = 1, int day = 1);  //全缺省函数构造
	Date(const Date& d);   //拷贝构造

	Date& operator=(const Date& d);   //赋值运算符的重载
	Date operator+(int days);

	int operator+(const Date& d);

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

	bool operator>(const Date& d)const;
};
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值