Postfix运算符重载中虚拟参数的目的?C++

2021-12-23 00:00:00 class methods parameters c++ c++11

当重载后缀运算符时,我可以做一些简单的事情

When overloading the postfix operator, I can do something simple like

Class Foo
{
private: 
   int someBS;
public:
   //declaration of  pre &postfix++
   Foo operator++();
   //rest of class not shown
};

Prefix 不需要带任何参数,所以当我定义它时,就像

Prefix doesn't need to take any parameters, so when I define it, something like

Foo Foo::operator()
{
   someBS ++;
   return *this;
}

这对我来说很有意义.

当我去定义后缀重载时,我必须包含一个虚拟的 int 参数

When I go to define the postfix overload I have to include a dummy int parameter

Foo Foo::operator++(int)
{
   Foo temp = *this;
   someBS ++;
   return temp;
}

我的问题是为什么?我从来没有在方法中使用它.前缀运算符不需要一个.返回 temp 值的后缀不依赖于虚拟参数.我知道如果我想要重载一个后缀操作符就是这样,我只想知道背后的原因.

My question is why? I don't ever use it in the method. The prefix operator doesn't require one. The postfix returning the temp value is not dependent on the dummy parameter. I know that if I want to overload a postfix operator that's how it's done, I just want to know the reason behind.

推荐答案

虚拟参数只是为了区分后缀和前缀运算符.在这两种情况下,名称 ++-- 是相同的,因此必须有some 方法来指定您要定义的那个.添加一个虚拟参数可能并不优雅,但任何替代方案都可能需要发明新的语法(可能是一个 postfix 关键字,这会破坏使用 postfix 作为标识符的代码).

The dummy parameter is simply there to distinguish between the postfix and prefix operators. The name ++ or -- is the same in both cases, so there has to be some way to specify which one you're defining. Adding a dummy parameter is perhaps not elegant, but any alternatives would probably have required inventing new syntax (perhaps a postfix keyword, which would break code that uses postfix as an identifier).

相关文章