运算符重载
2012-07-28 23:10 javaspring 阅读(380) 评论(0) 收藏 举报1、赋值运算符=
2、等于运算符==
3、加法运算符+
4、前向自加运算符++
5、后向自加运算符++
6、下标运算符[ ]
7、输入输出运算符<< 和 >>
8、转换运算符( )
9、实例代码
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class A;
ostream& operator<<(ostream &out,A &a);
istream& operator>>(istream &in,A &a);
class A{
private:
int b;
public:
A(){b=10;}
~A(){}
// 加法
A operator+(A&a)
{
A temp;
temp.b=b+a.b;
return temp;
}
// 加等于
A& operator+=(A&a)
{
b+=a.b;
return *this;
}
// 赋值
A& operator=(A&a)
{
if (a!=*this)
{
b=a.b;
}
return *this;
}
//相等
bool operator==(A&a)
{
return b==a.b;
}
// 前向++
A operator++()
{
b++;
return *this;
}
// 后向++ 区别前向++,加了个int形参
A operator++(int o)
{
A temp=*this;
b++;
return temp;
}
// 转换函数-- 形参列表为空,并且无返回类型
operator int()
{
return b;
}
//利用有元函数(可以访问类的私有成员)重载输入输出流
friend ostream& operator<<(ostream &out,A &a);
friend istream& operator>>(istream &in,A &a);
};
//有元函数重载输出流
ostream& operator<<(ostream &out,A &a)
{
out<<a.b<<endl;
return out;
}
//有元函数重载输入流
istream& operator>>(istream &in,A &a)
{
in>>a.b;
return in;
}
int main()
{
A a1;
cout<<a1;
A a2=a1++;
cout<<a2;
a2=++a1;
cout<<a2;
a2+=a1;
cout<<a2;
return 0;
}
浙公网安备 33010602011771号