运算符重载简单

运算符重载

为了增强程序的可读性,C++支持运算符重载 。所谓重载就是赋予这个操作符新的含义和功能,使之实现之前没有的功能。

运算符重载的特征为:

  1. operator + 合法的运算符 构成函数名(举例:重载<运算符的函数名:operator< )。
  2. 重载运算符以后,不能改变运算符的 优先级/结合性/操作数个数
    以下以“==”赋值运算符重载为例
{
public :
 Date()
 {}
 // 拷贝构造函数
 Date (const Date& d)
 {
 _year = d ._year;
 _month = d ._month;
 _day = d ._day;
 }
 // ==操作符的重载
 bool operator == (const Date& d)
 {
 return _year == d._year
 && _month == d._month
 && _day == d._day;
 }
private:
 int _year ;
 int _month ;
 int _day ;
};
void Test ()
{
 Date date1 ;
 Date date2 = date1;  //调用拷贝构造
 date2==date1;         //调用==运算符重载,可以使日期相等
 }
 


5个C++不能重载的运算符是哪些?.* / :: / sizeof / ?: / .

类的赋值操作符重载

1.赋值运算符的重载是对一个已存在的对象进行拷贝赋值 。
2.当程序没有显式地提供一个以本类或本类的引用为参数的赋值运算符重载函数时,编译器会自动生成这样一个赋值运算符重载函数

{
public :
 Date()
 {}
 // 拷贝构造函数
 Date (const Date& d)
 {
 _year = d ._year;
 _month = d ._month;
 _day = d ._day;
 }
 // 赋值操作符的重载
 // 1.思考为什么operator=赋值函数需要一个 Date&的返回值, 使用void做返回值可以吗? 
 Date& operator = (const Date& d)
 {
 // 2.这里的if条件判断是在检查什么?
 if (this != &d)
 {
 this->_year = d. _year;
 this->_month = d. _month;
 this->_day = d. _day;
 }
 return *this ;
 }
private:
 int _year ;
 int _month ;
 int _day ;
};
void Test ()
{
 Date date1 ;
 Date date2 = date1; // 调用拷贝构造函数
 Date date3 ;
 date3 = date1 ; // 调用赋值运算符的重载
 }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值