当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
重载操作符和函数对象
发布时间:2010/8/2 10:46:11 来源:城市学习网 编辑:ziteng
  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);//我理解为显式调用 [NextPage]   3.函数对象
  可以直接调用类的构造函数产生一个临时对象,作为参数传递给函数实参
  比如:
  Class GT_cls{
  public:
  GT_cls(int val):bool(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))  //简单的显式调用
  总结:
  由上述可以得出,重载操作符跟函数对象也是函数,只不过分显式跟隐式而已。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved