运算符重载

一、重载原则

  1. 赋值运算符的重载,用于在用户自定义的类型对象之间的彼此赋值;
  2. 算术运算符的重载,用于给数字类型增加算术属性;
  3. 关系运算符的重载,前提是类对象可进行逻辑比较;
  4. 重载算术和逻辑运算符时,注意满足交换性;
  5. “[ ]”的重载,用于检索容器类元素;
  6. “<<”和“>>”的重载,用于从I/O流中读写对象;
  7. “->”的重载,用于实现所谓的“智能指针(smart pointers)”;
  8. new、delete较少重载;
  9. 其他不得重载。

二、基本框架

  1. 重载赋值运算符
    Test &  Test:: operator = ( const  Test &  t)
    {
        
    if(&!= this){ ... }
        
    return *this;
    }
    1. 原因:解决类中包含指针的问题,避免析构时出错。
    2. 重载赋值运算符函数除了完成赋值操作外,还返回对被赋值对象的引用 
    3. 注意同拷贝构造函数的区别:若 被赋值对象不存在,则调用拷贝构造函数;否则调用赋值函数。
  2. 重载二元运算符
    // 成员运算符函数
    declare:
        Date 
    operator + ( int const ;
    defination:
        Date Date::
    operator + ( int  n)  const
        {
            ....
            
    return   * this ;
        }
            
    // 非成员运算符函数
    declare:
        friend Date 
    operator + ( int const  Date & );
    defination:
        Date Date::
    operator + ( int  n,  const  Date &  dt) 
        {
            Date
    *  d  =   new  Date();
            ....
            
    return   * d;
        }
  3. 重载一元运算符
  4. 重载“->”  运算符
    template < class  T >
    class  CountedPtr
    {
    public:
        
    //initialize pointer with existing pointer
        explicit CountedPtr(T* p = 0)
            : ptr(p), count(
    new long(1)) {}

        
    //copy pointer(one more owner)
        CountedPtr(const CountedPtr<T>& p) throw()
            : ptr(p.ptr),count(p.count) 
    {}

        
    //delete value if this was the last owner
        ~CountedPtr() throw()
        
    {
            dispose();
        }


        
    //assignment
        CountedPtr<T>& operator=(const CountedPtr<T>& p) throw()
        
    {
            
    if(this != &p)
            
    {
                dispose();
                ptr 
    = p.ptr;
                count 
    = p.count;
                
    ++*count;
            }

            
    return *this;
        }


        
    //acess the value to which the pointer refers
        T& operator*() const throw()
        
    {
            
    return *ptr;
        }

        T
    * operator->() const throw()
        
    {
            
    return ptr;
        }

    private:
        
    void dispose()
       
    {
            
    if(--*count == 0)
            
    {
                delete count;
                delete ptr;
            }

        }

    private:
        T
    * ptr;
        
    long* count;
    }
    ;
  5. 重载

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值