stl-c++常用操作符重载

     运算符重载在程序设计的过程中占有很重要的地位,现将最为常用的几个运算符重载方法罗列如下。其中,为了在vc下通过调试,使用了头文件#include<iostream.h>,若在gcc或者其他调试工具,仍建议写c++标准的头文件格式。

 

#include<iostream.h>
#include<algorithm>
//using namespace std;

class Thing
{
private:
 int id;
public:
 Thing():id(0){}
 Thing(int id_):id(id_){}
 ~Thing(){}
 //pre_increment ++thing
 Thing& operator++()
 {
  ++(this->id);
  return *this;
 }
 //post_increment thing++
 const Thing operator++(int)
 {
  Thing tmp=*this;
  ++(*this);
  return tmp;
  //临时对象tmp是前置式++效率优于后置式++的原因所在,在《c++标准库自学教程》一书中有涉及
 }
 //pre_decrement --thing
 Thing& operator--()
 {
  --(this->id);
  return *this;
 }
 //post_decrement thing--
 const Thing operator--(int)
 {
  Thing tmp=*this;
  --(*this);
  return tmp;
 }
 //dereference
 int& operator*()const
 {
  return (int&)id;
 }
 //input
 friend ostream& operator<<(ostream& out,const Thing& th);
 friend istream& operator>>(istream& in,Thing&th);
 //
 int get_id()const
 {
  return id;
 }
 void set_id(int new_id)
 {
  id=new_id;
 }
};

ostream& operator<<(ostream& out,const Thing& th)
{
 out<<" "<<th.get_id()<<" ";
 return out;
}
istream& operator>>(istream& in,Thing& th)
{
 int num;
 in>>num;
 th.set_id(num);
 if(in)
 {
  //
 }
 else
 {
  th=Thing();
 }
 return in;
}

int main()
{
 Thing one,two(6);
 Thing *ref=&two;
 cout<<one.get_id()<<endl;
 cout<<(++two)<<endl;
 cout<<one++<<endl;
    cout<<--two<<endl;
 cout<<two--<<endl;
 cin>>one;
 cout<<*ref<<endl;
 return 0;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值