重载操作符解析(二)

2014-11-24 12:12:44 · 作者: · 浏览: 1
操作符必须定义为成员函数。其次,要定义两个版本,一个是非const成员并返回引用。一个是为const成员并返回引用。
#include
using namespace std;

class Point {
int a[3];
public:
Point(int i, int j, int k) {
a[0] = i;
a[1] = j;
a[2] = k;
}
int &operator[](int &i) { return *(a + i); }
const int &operator[](const int &i) { return *(a + i); }

};

int main()
{
Point ob(1, 2, 3);
cout << ob[1];
return 0;
}
在sgi stl中,可以看到重载的情形:(够简洁的 )
reference operator[](size_type __n) { return *(begin() + __n); }
const_reference operator[](size_type __n) const { return *(begin() + __n); }
⒌ 成员访问操作符
C++中支持重载解引用操作符(*)和箭头操作符(->),其中, 箭头操作符必须定义为类成员函数,解引用则两者皆可。看看以下的用法:
_Reference operator*() const {
_BidirectionalIterator __tmp = current;
return *--__tmp; // 返回值
}

pointer operator->() const { return &(operator*()); } // 返回指针
⒍ 自增和自减操作
a++,++a,--b,b--。是不是有点烦人?但是看了重载的意义之后,你就知道,这个东西是不烦人的。也知道了在for循环中为什么要强调用++a了。
C++中,并没有特别要求说一定要为成员函数,但是为成员函数是一个不错的选择 。
还有要注意的是 :
① 为了与内置类型一致,前缀式操作符应返回被增量或减量对象的引用;
② 后缀式返回旧值,应作为值返回,不是返回引用,所以返回不用引用。
现在看看如何使用:
Point &operator++(); // 为了与内置类型一致,前缀式操作符应返回被增量或减量对象的引用
Point operator++(int); // 返回旧值,应作为值返回,不是返回引用

Point &operator--();
Point operator--(int);
....
// 前增
Point &Point::operator++()
{
++this->x;
++this->y;
return *this;
}

// 后增
Point Point::operator++(int)
{
Point temp = *this;
++this->x;
++this->y;
return temp;
}

// 前减
Point &Point::operator--()
{
--this->x;
--this->y;
return *this;
}

// 后减
Point Point::operator--(int)
{
Point temp = *this;
--this->x;
--this->y;
return temp;
}
知道为什么说要强调说前缀式了吗 ?看看前缀和后缀的区别,你就知道那个效率会高。。。
总结,这些东西写的有点辛苦,写写停停的。请大牛指正其中不妥之处,小菜谢谢了。。。

摘自 云端小飞象cg