search

Home  >  Q&A  >  body text

c++ - 为什么叫做操作符重载?

如题,按重载的定义,应该具有相同的函数名才行啊,为什么是叫操作符重载,而不是操作符重写?

PHPzPHPz2807 days ago671

reply all(5)I'll reply

  • PHPz

    PHPz2017-04-17 11:46:05

    First let’s clarify the difference between overloading and rewriting:

    1. Overloading generally refers to two different functions in the same scope using the same name, but they must have different parameter lists, such as different parameter types or different number of parameters.

    2. Override refers to reimplementing the virtual function in the base class in the subclass (remember, it must be a virtual function! If the subclass reimplements a non-virtual function in the base class, It should be called "hide"!).

    Now let’s get it straight: Suppose you overload the operator “+”. In fact, the function name you overload is “+”, which has the same function name as the original (built-in) “+”. But your overloaded "+" and the original "+" should have different parameter lists (otherwise you wouldn't need to overload). In fact, C++ requires that when overloading an operator, you must ensure that at least one parameter is your custom class type. If you overload it like this

    int operator+(int a, int b);
    

    The compiler will report an error. You will find that the whole process seems to have nothing to do with virtual functions. Therefore, operator overloading can only be called "overloading", not "rewriting".

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 11:46:05

    You think of an operator as a function, but in fact it is a function. Personal opinion

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:46:05

    Operator overloading is a concept as a whole. Why do you have to take it apart and look at it?

    reply
    0
  • 迷茫

    迷茫2017-04-17 11:46:05

    Corresponds to the original text:

    override: function override (overwriting is too easy to misunderstand)
    overload: overload
    operator overload:Operator overload

    The reason why it is not called overwriting is because this feature has nothing to do with inheritance. Overloading focuses more on its extended nature.

    reply
    0
  • 阿神

    阿神2017-04-17 11:46:05

    Similar to function overloading. . .

    reply
    0
  • Cancelreply