Purpose of Dummy Parameter in Postfix Operator Overload? c++

前端 未结 3 587
栀梦
栀梦 2021-01-06 03:28

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

Class Foo
{
private: 
   int someBS;
public:
   //declaration of  pre &postfix++
           


        
相关标签:
3条回答
  • 2021-01-06 03:44

    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).

    0 讨论(0)
  • 2021-01-06 04:07

    Citing C++reference here:

    Prefix versions of the built-in operators return references and postfix versions return values, and typical user-defined overloads follow the pattern so that the user-defined operators can be used in the same manner as the built-ins.

    Explaining this logically:

    int a = 3;
    int b = 0;
    
    int c = a + ++b;
    int d = a++ + b;
    

    In the third line, ++b gives you a reference to the updated value; in the fourth line, that's not possible: a has to be increased, so a value-copy is made, and added to b. That dictates different semantics for the operators.

    In fact, just to avoid having another operator name:

    The int parameter is a dummy parameter used to differentiate between prefix and postfix versions of the operators. When the user-defined postfix operator is called, the value passed in that parameter is always zero, although it may be changed by calling the operator using function call notation (e.g., a.operator++(2) or operator++(a, 2)).

    0 讨论(0)
  • 2021-01-06 04:09

    To quote cppreference:

    The int parameter is a dummy parameter used to differentiate between prefix and postfix versions of the operators.

    The quote says it all, because how else would you differentiate prefix and postfix?

    Let's just say that you don't need the int parameter, then the prefix (Foo operator++()) and postfix (Foo operator++()) would be exactly the same! How would the compiler know which one you meant? That's why there is this dummy int parameter.

    0 讨论(0)
提交回复
热议问题