Difference between operator and function in C++?

后端 未结 8 503
夕颜
夕颜 2021-02-01 08:31

I could use some help understanding the following in C++, particularly the difference between an operator and a function:

  • What is an operator?
  • What is a f
8条回答
  •  生来不讨喜
    2021-02-01 08:57

    What is operator?

    An operator is generally an operation performed on a variable given some form of punctuation. For example, the default behavior of operator+ between two integers is to add them.

    What is function?

    A function is a subroutine -- a reuseable block of code.

    What is the difference between them?

    Nothing, as far as user code is concerned, except for syntax. Note that if you override operator||, operator&&, or (to a lesser extent) operator,, you change the semantics of the built in operator semantics. In the case of && and ||, you make the operation which is normally short circuiting into an operation which is not. In the case of the comma, you would need to ensure that you evaluate the arguments left to right, as the comma operator normally behaves in this way.

    Is user-defined operator+() a function or operator?

    Neither. It is a user defined operator overload. A function name cannot start with the keyword operator, and an operator is simply the actual punctuation mark used to invoke the operator overload, i.e. + or -. EDIT: Note that while technically speaking it is not a function, it does have the semantics of a function call, as demonstrated in @Martin York's excellent answer.

    Can operator operate on operands at compile-time? Do they always operate at compile time? (like sizeof() in C++)

    No, sizeof cannot be overloaded. If you want some form of compile time operation done, you need to use something like template metaprogramming. Note that if the compiler is able to do the calculation at compile time it may elide the call into your overloaded operator, of course.

提交回复
热议问题