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

2023-07-01C/C++开发问题
5

本文介绍了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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6