原文: https://www.programiz.com/cpp-programming/increment-decrement-operator-overloading
要理解此示例,您应该了解以下 C++ 编程主题:
在本教程中,以最佳方式重载++和递减--运算符,即,如果++运算符对一个对象进行运算,则将数据成员的值增加 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;这是因为上述程序中的运算符函数的返回类型为空。
这是上述程序的少量修改,因此您可以使用代码obj1 = ++obj。
#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;。 这是因为,从运算符函数返回的temp被存储在对象obj中。
由于运算符函数的返回类型为Check,因此您还可以将obj的值分配给另一个对象。
注意,=(赋值运算符)不需要重载,因为该运算符已在 C++ 库中重载。
到目前为止,递增运算符的重载只有在以前缀形式使用时才是正确的。
这是对上述程序的修改,以使此函数对于前缀形式和后缀形式均有效。
#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当递增运算符以前缀形式重载时;Check operator ++ ()被调用,但是当递增运算符以后缀形式重载时;Check operator ++ (int)被调用。
注意,括号内的int。 此int向编译器提供信息,它是运算符的后缀版本。
不要混淆此int不表示整数。
递减运算符可以像递增运算符一样重载。
#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同样,一元运算符,例如:!,〜等也可以类似的方式重载。