下面是一元操作符++的操作符重载代码
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator++ () {
feet = feet+1;
inches = inches+1;
return Distance(feet, inches);
}
};
int main() {
Distance D1(11, 10), D2(-5, 11);
++D1; // increment by 1
D1.displayDistance(); // display D1
++D2; // increment by 1
D2.displayDistance(); // display D2
return 0;
}当我使用上面的代码时,我可以成功地使用前缀操作符++D1和++D2,但是我不知道如何重载后缀操作符D1++和D2++,即使我在上面的代码中尝试了这些,这表明了错误,那么我们如何分别对后缀和前缀使用操作符重载的概念呢?
发布于 2022-03-02 05:23:58
如果您需要post/dec,则代码为:
Distance operator++ (int) {
feet = feet+1;
inches = inches+1;
return Distance(feet, inches);
}我们在形式参数中使用int。它只是机箱之间的后置/预装不同。操作符的前缀形式与任何其他一元运算符的声明方式完全相同;后缀表单接受int类型的额外参数。
发布于 2022-03-02 05:03:25
对于后缀operator++,您必须指定一个int类型的额外(未使用)参数,如下所示:
class Distance {
//other code as before
public:
Distance operator++(int);//declaration for postfix operator++
};
//other code as before
//definition for postfix operator++
Distance Distance::operator++(int)
{
Distance ret = *this; // save the current value
++*this; // use prefix ++
return ret; // return the saved state
}见演示。
解释
定义前缀和后缀运算符时存在问题,因为这两个版本都使用相同的符号,这意味着这些运算符的重载版本具有相同的名称。此外,它们的操作数和类型也是相同的。
因此,为了解决这个问题,后缀版本增加了一个int类型的参数。当我们使用后缀操作符时,编译器/隐式提供0作为这个参数的参数。
https://stackoverflow.com/questions/71317624
复制相似问题