您的位置:首页 > 编程语言 > C语言/C++

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

2009-12-05 18:42 295 查看
运算符重载在程序设计的过程中占有很重要的地位,现将最为常用的几个运算符重载方法罗列如下。其中,为了在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: