zoukankan      html  css  js  c++  java
  • 重载操作符和函数对象

    1.重载操作符跟重载函数一样的,只不过要区分成员的和非成员的

    成员的重载操作符,第一个参数默认了是this 指针形参,所以重载操作符作为成员函数,都应该是右操作符

    比如:

    ostream& operator<<(ostream &out)  //右操作运算符  调用方式:Screen s;s<<std::cout;
    {   
          out<<'('<<height<<','<<width<<')'<<*(pContents)<<std::endl;   
          return out;
     }
    friend ostream& operator<<(ostream& out,Screen& s) //友原函数的重载操作符
    {  
         out<<'('<<s.height<<','<<s.width<<')'<<*(s.pContents)<<std::endl;  
         return out;
    }
    上述一个成员,一个非成员重载方式,调用相应如下:
     s1<<std::cout; // 调用的是作为成员函数的重载操作符
     std::cout<<s2; //调用的是友原函数

    2.至于返回值,值得注意的地方是:

    何时返回类型的引用值何时返回类类型,应该跟内置的操作符一致;

    比如+=返回引用,+则应该返回类类型本身。

    如下:

    Screen& operator+=(Screen& rhs)  //复合赋值操作符
    {
    height += rhs.height;
    width  += rhs.width;
    *pContents += *(rhs.pContents);
    return *this;
    }                
    friend Screen operator+(Screen& s1,Screen& s2 )
    {
    Screen s;
    s.width = s1.width+s2.width;
    s.height = s1.height+s2.height;
    *(s.pContents) = *(s1.pContents)+*(s2.pContents);
    return s;
    }
    //可以两种方式调用:
    Screen s0,s1,s2;
       s0=s1+s2;  //隐式调用
       //或者
       s0=operator+(s1,s2);//我理解为显式调用 

    3.函数对象

    可以直接调用类的构造函数产生一个临时对象,作为参数传递给函数实参

    比如:

    Class GT_cls{
    public:      
    GT_cls(int val):bound(val){}      
    bool operator(const string s) ;
    {return s.size()>=bound;}
    private:      
    std::string::size_type bound;
    };
    然后
    count_if(word.begin(),word.end(),GT_cls(6));  //count_if标准库算法 这里GT_cls先构造临时对象,然后count_if传递word对象进GT_cls然后调用函数()//C++ Primer里面的例子     

    再比如如下:

    struct IterOp{
    virtual void operator()(std::vector<char>::const_iterator& iter) = 0;
    };
    struct IterAdd : public IterOp{
    void operator()(std::vector<char>::const_iterator& iter){++iter;}
    };
    struct IterSub : public IterOp{
    void operator()(std::vector<char>::const_iterator& iter){--iter;}
    };
    IterOp* ops[] = {new IterAdd, new IterSub};for (; iter != flags[index]; ops[index]->operator()(iter))  //简单的显式调用

    总结:

    由上述可以得出,重载操作符跟函数对象也是函数,只不过分显式跟隐式而已。

    点击这里给我发消息
  • 相关阅读:
    .NET:如何应对边界异常?
    由极点五笔到QQ五笔的转换想到的
    【转】七个受用一生的心理寓言
    proverb: better late than never
    背单词软件supermemo从2006版升级到2008版
    今天解决一个异步刷新TreeView的问题
    开始尝试换成Windows 7了
    southpaw
    用supermemo背单词达到6000词条
    Averse, Adverse
  • 原文地址:https://www.cnblogs.com/charm/p/1788303.html
Copyright © 2011-2022 走看看