gpt4 book ai didi

c++ - 为什么使用 int 作为后增量运算符重载的参数?

转载 作者:太空狗 更新时间:2023-10-29 19:59:31 26 4
gpt4 key购买 nike

据我所知,这是重载后增量运算符的方法:

const MyClass& MyClass::operator++(int);

为什么它有 int 作为参数?

最佳答案

D&E , §11.5.3:

I conisdered the obvious solution, adding the keywords prefix and postfix to C++ [ ... ]However I received the usual howl of outrage from people who dislike new keywords. Several alternatives that did not involve new keywords were suggested. For example:

   class Ptr_to_X {
X ++operator(); // prefix ++
X operator++(); // postfix ++
};

or

   class Ptr_to_X {
X& operator++(); // postfix because it
// returns a reference
x operator++(); // prefix because it
// doesn't return a reference
};

I considered the former too cute and the latter too subtle. Finally I settled on:

   class Ptr_to_X {
X operator++(); // prefix: no argument
X operator++(int); // postfix: because of the argument
};

This may be too cute and too subtle, but it works, requires no new syntax, and has a logic to the madness. Other unary operators are prefix and take no arguments when defined as member functions. The "odd" and unused dummy int argument is used to indicate the odd postfix operators. In other words, in the postfix case, ++ comes between the first (real) operand and the second (dummy) argument and is thus postfix.

These explanations are needed because the mechanism is unique, and therefore a bit of a wart. Given a choice I would probably have introduced the prefix and postfix keywords, but that didn't appear feasible at the time.

关于c++ - 为什么使用 int 作为后增量运算符重载的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12740378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com