Why is it called operator overloading?

后端 未结 2 1716
挽巷
挽巷 2021-01-21 07:26

If the following class, Foo, is defined. It is said it overloads the unary ampersand (&) operator:

class Fo         


        
相关标签:
2条回答
  • 2021-01-21 08:04

    You can't redefine a function or operator in C++, you can add only new use to it, defining new set of arguments. That's why it called overloading instead of redefining.

    When you overload operator as a member of class you

    1) defined it with first argument supposed to be an instance of that class

    2) gave it access to all members of that class.

    There are still definitions of operator& with different arguments and you have a non-zero chance to create situation where use of operator would be ambigous.

    0 讨论(0)
  • 2021-01-21 08:15

    Consider the following code:

    int x;
    Foo y;
    &x; // built-in functionality
    &y; // y.operator&();
    

    We have two variables of different types. We apply the same & operator to both of them. For x it uses the built-in address-of operator whereas for y it calls your user-defined function.

    That's exactly what you're describing as overloading: There are multiple functions (well, one of them is the built-in functionality, not really a "function") and they're selected based on the type of the operand.

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