Is it not possible to call C++ operators manually?

后端 未结 6 577
执念已碎
执念已碎 2020-12-31 04:13

I\'m trying to understand operators in C++ more carefully.

I know that operators in C++ are basically just functions. What I don\'t get is, what does the function lo

6条回答
  •  一生所求
    2020-12-31 05:02

    Using C++ standardese, the function call syntax (operator+(x, y) or x.operator+(y)) works only for operator functions:

    13.5 Overloaded operators [over.oper]

    4. Operator functions are usually not called directly; instead they are invoked to evaluate the operators they implement (13.5.1 - 13.5.7). They can be explicitly called, however, using the operator-function-id as the name of the function in the function call syntax (5.2.2). [Example:

        complex z = a.operator+(b); // complex z = a+b;
        void* p = operator new(sizeof(int)*n);
    

    —end example]

    And operator functions require at least one parameter that is a class type or an enumeration type:

    13.5 Overloaded operators [over.oper]

    6. An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

    That implies that an operator function operator+() that only takes ints cannot exist per 13.5/6. And you obviously can't use the function call syntax on an operator function that can't exist.

提交回复
热议问题