测试程序
详细分析见代码注释
#include<iostream>
#include <bitset>
using namespace std;
class Point
{
private:
int x;
public:
Point(int x1) :x(x1) {};
int getx() { return this->x; };
Point& operator++();//成员函数定义自增
Point operator++(int n); //后缀可以返回一个const类型的值
Point& operator--();//成员函数定义自减
Point operator--(int n);//后缀可以返回一个const类型的值
};
Point& Point::operator++()//++obj
{
cout << "Point& Point::operator++() ++obj" << endl;
x++;
return *this; //通过引用返回*this ,也就是返回变化之后的数值
}
Point Point::operator++(int n)//obj++
{
cout << "const Point Point::operator++(int n) obj++" << endl;
Point temp = *this;
(this->x)++;
return temp; //返回原状态的拷贝
}
Point& Point::operator--()//--obj
{
cout << "Point& Point::operator--() --obj" << endl;
x--;
return *this;
//通过引用返回*this ,也就是返回变化之后的数值
}
Point Point::operator--(int n)//obj--
{
cout << "const Point Point::operator--(int n) obj--" << endl;
Point temp = *this;
x--;
return temp;
// 返回原状态的拷贝
}
int main()
{
Point a(1);
Point b(2);
cout << "a++" << "\t";
a++;//隐式调用成员函数operator++(0),后缀表达式
cout << "++a" << "\t";
++a;//隐式调用成员函数operator++(),前缀表达式
cout << "b--" << "\t";
b--;//隐式调用友元函数operator--(0),后缀表达式
cout << "--b" << "\t";
--b;//隐式调用友元函数operator--(),前缀表达式
cout << "*************下面测试++组合形式********************" << endl;
cout << "a=" << a.getx() << endl;
cout << "(++a)++" << endl;
//(a++)++; //错误调用,(a++)返回的是拷贝对象值,对其++不影响a,没有意义
(++a)++; //正确,(++a)返回本身引用
cout << "a=" << a.getx() << endl;
cout << "*************下面测试--组合形式********************" << endl;
cout << "b=" << b.getx() << endl;
cout << "(--b)--" << endl;
//(b--)--; //错误调用,(b--)返回的是拷贝对象值,对其--不影响b,没有意义
(--b)--; //正确,(--b)返回本身引用
cout << "b=" << b.getx() << endl;
}
测试结果如下:
标准库程序
上面测试程序的写法参考了标准库的程序,下面代码来自stl源码 stl_list.h 中iterator相关的运算符重载
template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
typedef __list_iterator<T, T&, T*> iterator; //迭代器
typedef __list_iterator<T, Ref, Ptr> self;
self& operator++() {
node = (link_type)((*node).next); //node指向下一个节点
return *this;
}
self operator++(int) {
self tmp = *this;
++*this; //交给上面的self& operator++()处理
return tmp; //返回原状态拷贝
}
self& operator--() {
node = (link_type)((*node).prev); //node指向上一个节点
return *this;
}
self operator--(int) {
self tmp = *this;
--*this; //交给上面的self& operator++()处理
return tmp; //返回原状态拷贝
}
可以发现对iterator来说,iterator++或者iterator–都有一次构造函数,且实际调用的是++iterator和–iterator来处理,效率低下,
所以我们使用迭代器来说,尽量使用++iterator和–iterator操作。