Purpose of Dummy Parameter in Postfix Operator Overload? c++(Postfix运算符重载中虚拟参数的目的?C++)
问题描述
当重载后缀运算符时,我可以做一些简单的事情
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).
这篇关于Postfix运算符重载中虚拟参数的目的?C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Postfix运算符重载中虚拟参数的目的?C++
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
