重载后缀和前缀运算符 [英] overloading postfix and prefix operators
问题描述
请考虑以下代码
#include <iostream>
using namespace std;
class Digit
{
private:
int m_digit;
public:
Digit(int ndigit=0){
m_digit=ndigit;
}
Digit& operator++();//prefix
Digit& operator--(); //prefix
Digit operator++(int);
Digit operator--(int);
int get() const { return m_digit;}
};
Digit& Digit::operator++(){
++m_digit;
return *this;
}
Digit& Digit::operator--(){
--m_digit;
return *this;
}
Digit Digit::operator++(int){
Digit cresult(m_digit);
++(*this);
return cresult;
}
Digit Digit::operator--(int){
Digit cresult(m_digit);
--(*this);
return cresult;
}
int main(){
Digit cDigit(5);
++cDigit;
cDigit++;
cout<<cDigit.get()<<endl;
cout<<cDigit.get()<<endl;
return 0;
}
这里实现了postfix和prefix运算符的两个版本,我已经读到引入另一个所谓的哑元参数是有区别的,但是我怀疑我们是否看到它们的声明
here is implemented two version of postfix and prefix operators,i have read that difference is made by introduce another so called dummy argument,but i have question if we see declaration of these
Digit& operator++();//prefix
Digit& operator--(); //prefix
Digit operator++(int);
Digit operator--(int);
它们之间的区别是&标记,那么为什么必须要使用伪参数?在这两种情况下,例如++运算符都写在该参数之前,这并不意味着它们相同吗?
they are differed by & mark,so why it is necessary dummy argument?and also in both case for example ++ operator is written before the argument and does not it means that they are same?
推荐答案
前和后递增是两个不同的运算符,并且需要单独的重载.
The pre- and post-increment are two distinct operators, and require separate overloads.
C ++不允许仅在返回类型上进行重载,因此像您的示例中那样使用不同的返回类型不足以消除这两种方法的歧义.
C++ doesn't allow overloading solely on return type, so having different return types as in your example wouldn't be sufficient to disambiguate the two methods.
哑元参数是C ++设计人员为消除歧义而选择的机制.
The dummy argument is the mechanism that the designer of C++ chose for the disambiguation.
这篇关于重载后缀和前缀运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!