为什么后缀增量运算符采用虚拟参数? [英] Why does the postfix increment operator take a dummy parameter?

查看:255
本文介绍了为什么后缀增量运算符采用虚拟参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看这些函数签名:

 class Number {
 public:
   Number& operator++ ();    // prefix ++
   Number  operator++ (int); // postfix ++
 }; 

前缀不接受任何参数,但postfix。为什么?我想我们可以用不同的返回类型来识别它们。

Prefix doesn't take any parameter but postfix does. Why? I thought we can recognize them with different return types.

推荐答案

前缀和后缀 ++ 是不同的运算符。使用标准 Foo操作符(Foo&)样式声明,没有明显的方法来区分两者。而不是提出一些新的语法,如 Foo符号运算符(Foo&),这将使它成为一个特殊情况不像所有其他运算符,可能有点疼痛解析,语言设计者想要一些其他解决方案。

Prefix and postfix ++ are different operators. With the standard Foo operator symbol(Foo &) style declaration there was no obvious way to distinguish the two. Rather than come up with some new syntax like Foo symbol operator(Foo &) which would make it into a special case unlike all the other operators and likely a bit of a pain to parse, the language designers wanted some other solution.

他们选择的解决方案有点奇怪。他们注意到所有其他的'postfix'运算符(即在它们的操作数之一之后发生的运算符)实际上是采用两个参数的中缀运算符。例如,简单的 + - 。在这个基础上,语言设计者决定使用一个随机虚拟参数来区分前缀和后缀 ++

The solution they chose was somewhat bizarre. They noted that all the other 'postfix' operators (i.e. operators that occurred after one of their operands) were actually infix operators that took two arguments. For example, plain old + or -. On this basis the language designers decided that having a random dummy argument would be a good way to distinguish between prefix and postfix ++.

IMHO,它是作为C ++进化的陌生人决策之一。但你有它。

IMHO, it's one of the stranger decisions made as C++ evolved. But there you have it.

由于两个原因,你不能基于返回类型来区分它们。

And you can't distinguish them based on return type for two reasons.

第一个是,C ++中的函数不能在返回类型上重载。您不能有两个函数具有相同的名称和参数类型列表,但不同的返回值。

The first is that functions in C++ cannot be overloaded on return type. You cannot have two functions that have identical names and parameter type lists but different return values.

第二是该方法不够鲁棒或不够灵活,无法处理所有可能的实现前缀和后缀 ++

The second is that method would not be robust or flexible enough to handle all possible implementations of prefix and postfix ++.

例如,您可能需要一个后缀 + 返回一个引用类型,如果你曾经调用它的唯一原因是调用与应用它的变量的值无关的副作用。在我看来,这将是一个非常糟糕的实现,但C ++不是判断什么样的愚蠢的代码,你想写,而是关于使你能写任何代码,你认为适合的情况。并且强制你对前缀 ++ 和后缀 ++ 使用一种特定风格的返回类型将会与精神。

For example, you might want a postfix ++ that returned a reference type if the only reason you ever called it was to invoke a side-effect unrelated to the value of the variable you were applying it to. In my opinion, that would be a very bad implementation, but C++ is not about judging what kinds of stupid code you want to write, but about enabling you to write whatever code it is you think appropriate to the situation. And forcing you to use one particular style of return type for prefix ++ and postfix ++ would be contrary to that spirit.

这篇关于为什么后缀增量运算符采用虚拟参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆