现在的位置: 首页 > 综合 > 正文

C++中的运算符重载(二)

2014年08月10日 ⁄ 综合 ⁄ 共 2052字 ⁄ 字号 评论关闭

1.C++中重载++操作符,

C++中重载前++操作符,使用成员函数重载,

,用如下形式:

<类名>   operator ++()

{

···// 函数体

}

用成员函数重载后++操作符,形式为:

<类名>   operator ++(int)

{

···// 函数体

}

它们的区别在于,后++操作符的形参表多了一个int,在调用时,前++操作符的调用方法为  对象名.operator++(),++的调用方法为  对象名.operator
++(0)

下面的代码实现了重载++ -- [] *操作符。

# include <iostream>
using namespace std;
# include <vector>
template<typename T>
class Check{
public:
	Check(T *b,T* e):beg(b),end(e),curr(b){}
	Check &operator ++(); 
	Check &operator --();
	Check &operator ++(int);
	Check &operator --(int);
	T& operator [](const size_t index);
	const T& operator [](const size_t index) const;
	T &operator*() const;
private:
	T *beg;
	T *end;
	T *curr;
};

template <typename T>
Check <T> & Check<T>::operator++()
{
if(curr==end)
	throw out_of_range("increment past the end of check");
curr++;
return *this;
}
template <typename T>
Check <T>& Check<T>::operator--()
{
if(curr==beg)
	throw out_of_range("decrement past the head of check");
curr--;
return *this;
}
template <typename T>
Check <T>& Check<T>::operator++(int)
{
Check t(*this);
++*this;
return t;
}
template <typename T>
Check <T> & Check <T>::operator--(int)
{
Check t(*this);
--(*this);
return t;
}
template <typename T>
T& Check <T>::operator[](const size_t index)
{
if (beg+index>end)
	throw out_of_range("out of range");
return *(beg+index);
}
template <typename T>
const T & Check <T>::operator[](const size_t index) const
{
	if(beg+index>end)
		throw out_of_range("index out of range");
	return *(beg+index);
}
template <class T>
T & Check<T>::operator *() const
{
if(curr==end)
	throw out_of_range("index out of range");
return *curr;
}

int main()
{
	int a[10]={1,2,3,4,5,6,7,8,9,0};
	const Check <int> t(a,a+10);
	Check <int> t2(a,a+10);
	Check <int> t3(a,a+3);
	cout<<*t<<endl;
	t3=t2.operator++();
	cout<<*t3<<endl;
	t2.operator--();
	Check <int> t4(a,a+5);
	t4=t2.operator++(0);
	cout<<*t4<<endl;
	cout<<t4.operator[](2)<<endl;
	cin.get();
return 0;
}

2 重载<<操作符

当定义符合标准库iostream规范的输入或输出操作符的时候,必须定义为友元操作符,否则,左操作数将只能是该类类型的对象。

Sales_item item;

Item <<cout;

这个用法与为其它类型定义的输出操作符的正常使用方式相反。类通常将IO操作符设为友元。

# include <iostream>
using namespace std;
class test
{
public:
	test(int i):x(i){}
	friend ostream& operator<<(ostream & os,test & a);
	int getx(){return x;}
private:
	int x;
}; 
ostream& operator<<(ostream & os,test & a)
{
os<<a.getx()<<endl;
return os;
}
int main()
{
	test a(1);
	cout<<a;
	cin.get();
return 0;
}

抱歉!评论已关闭.