当前位置:   article > 正文

运算符重载与const对象_返回const对象的普通函数重载算术运算符

返回const对象的普通函数重载算术运算符

运算符重载与函数重载

关键字operator加上运算符名的函数称为运算符函数

operator+(8,9)			//A
operator+(8.1,9.1)		//B
    
    
int operator+(int,int)		//A1
double operator+(double,double)		//B1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

根据函数重载规则,(A)调用A1, (B)调用B1

这样函数重载机制实现了运算符重载,运算符重载实际是函数重载

运算符重载规则
不可被重载的运算符
.成员选择运算符
.*成员指针运算符
::作用域分辨符
?:三目选择运算符
sizeof计算数据大小运算符
运算符的重载规则
重载后运算符的优先级与结合性不会改变
不能改变原运算符操作的个数
不能重载C++没有的运算符
不能改变运算符的原有意义
不能重载非静态成员(全局成员)
赋值运算符重载

格式

  • 参数类型:const T&(要做右值)
  • 返回值:T&
  • 检查是否给自己赋值
  • 返回*this,要符合连续赋值的含义

举例:

class Day
{ 
public :
 Day(int year = 1900, int month = 1, int day = 1)
   {
        _year = year;
        _month = month;
        _day = day;
   }
 
 Day (const Day& d)
   {
        _year = d._year;
        _month = d._month;
        _day = d._day;
   }
 
 Day& operator=(const Day& d)//在赋值运算符中运用引用就可以提高效率
 {
 		if(this != &d)
       {
            _year = d._year;
            _month = d._month;
            _day = d._day;
       }
        
        return *this;		//return Day(_year,_month,_day) 函数返回
 }
private:

 int _year ;
 int _month ;
 int _day ;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

使用了this指针返回对象,和函数返回的区别:

函数返回对象时需要调用构造函数建立临时对象

this指针返回对象不需要 调用构造函数,但会调用拷贝构造函数。

const成员

const修饰的成员函数,称之为const成员函数

class Day
{
    public:
    void Display()const   //void Display(const Day* this)修饰后
    {					//cout<<*this->_year;
        cout<<_year;
	}
    private:
    int _year;
    
};


int main()
{
	Day d1;
	d.


return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

调用时要注意,权限只能缩小或者平移,不能放大

    class Day
    {
    public:
        void Display()   //没有const修饰
        {					
            cout << _year;
        }
    private:
        int _year=1;

    };


    int main()
    {
        const Day  d1;//报错
        d1.Display();


            return 0;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

函数不加const就无法被const对象调用

取地址和const取地址操作符重载
class Day
{ 
public :
 Day* operator&()
 {
 return this ;

 }
 const Day* operator&()const
 {
 return this ;
 }
private :
 int _year ; 
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/838190
推荐阅读
相关标签
  

闽ICP备14008679号