在本教程中,递增 ++ 和递减--运算符以最佳方式重载,即,如果 ++ 运算符对对象进行操作,则将数据成员的值增加 1,如果,则将数据成员的值减少 1--使用运算符。
示例 1: 前缀 ++ 递增运算符重载,无返回类型
#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(0) { } void operator ++() { ++i; } void Display() { cout << "i=" << i << endl; } }; int main() { Check obj; // Displays the value of data member i for object obj obj.Display(); // Invokes operator function void operator ++( ) ++obj; // Displays the value of data member i for object obj obj.Display(); return 0; }
输出
i=0 i=1
最初声明对象
obj时,对象
obj的数据成员
i的值为0(构造函数初始化
i 到 0)。
当在
obj 上操作++ 运算符时,会调用运算符函数
void operator++( )
将数据成员
i 的值增加到1.
这个程序是不完整的,你不能使用代码:
obj1 = ++obj;
这是因为上面程序中操作符函数的返回类型是void。
这里对上面的程序稍作修改,以便您可以使用代码
obj1 = ++obj
。
示例 2: 带返回类型的 Prefix Increment ++ 运算符重载
#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(0) { } // return type is Check Check operator ++() { Check temp; ++i; temp.i = i; return temp; } void Display() { cout << "i = " << i << endl; } }; int main() { Check obj, obj1; obj.Display(); obj1.Display(); obj1 = ++obj; obj.Display(); obj1.Display(); return 0; }
输出
i = 0 i = 0 i = 1 i = 1
这个程序与上面的程序类似。
唯一的区别是,运算符函数的返回类型是
Check 在这种情况下允许使用两种代码
++obj;
obj1 = + +obj;
.这是因为,operator 函数返回的
temp 存储在对象
obj 中。
由于操作符函数的返回类型是
Check,你也可以将
obj的值赋给另一个对象。
请注意,=(赋值运算符)不需要重载,因为该运算符已在 C++ 库中重载。
示例 3: 后缀增量 ++ 运算符重载
到目前为止,增量运算符的重载仅在以前缀形式使用时才成立。
这是对上述程序的修改,使其适用于前缀形式和后缀形式。
#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(0) { } Check operator ++ () { Check temp; temp.i = ++i; return temp; } // Notice int inside barcket which indicates postfix increment. Check operator ++ (int) { Check temp; temp.i = i++; return temp; } void Display() { cout << "i = "<< i <<endl; } }; int main() { Check obj, obj1; obj.Display(); obj1.Display(); // operator function is called, only then value of obj is assigned to obj1 obj1 = ++obj; obj.Display(); obj1.Display(); // Assigns value of obj to obj1, only then operator function is called. obj1 = obj++; obj.Display(); obj1.Display(); return 0; }
输出
i = 0 i = 0 i = 1 i = 1 i = 2 i = 1
当增量运算符以前缀形式重载时;
检查运算符++()
被调用但是,当增量运算符以后缀形式重载时;
检查运算符++(int)
被调用。
注意,括号内的
int。这个
int 向编译器提供信息,表明它是运算符的后缀版本。
不要混淆这个
int 不表示整数。
示例4: 减量的运算符重载——运算符
减量运算符可以以与增量运算符类似的方式重载。
#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(3) { } Check operator --() { Check temp; temp.i =--i; return temp; } // Notice int inside barcket which indicates postfix decrement. Check operator --(int) { Check temp; temp.i = i--; return temp; } void Display() { cout << "i = "<< i <<endl; } }; int main() { Check obj, obj1; obj.Display(); obj1.Display(); // operator function is called, only then value of obj is assigned to obj1 obj1 =--obj; obj.Display(); obj1.Display(); // Assigns value of obj to obj1, only then operator function is called. obj1 = obj--; obj.Display(); obj1.Display(); return 0; }
输出
i = 3 i = 3 i = 2 i = 2 i = 1 i = 2
此外,一元运算符如: !、~等可以以类似的方式重载。