Difference between operator and function in C++?

后端 未结 8 504
夕颜
夕颜 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 09:03

    There is no huge difference between functions and operators. You can think of an using operator, e.g., 'a+b', as a shortcut to the function operator+(a,b) which is defined for the types of a and b. Of course, operators on primitive types (like integers) and a few other exceptions are not necessarily defined like this.

    Thus, to answer a few of your specific questions:

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

    A function that implements an operator.

    Can operator operate on operands at compile-time? Do they always operate at compile time?

    Since it is a function, it operates at run time, but in some cases compiler optimizations can do work at compile time for certain operators. I'm not 100% sure why you're asking this, so perhaps there is something I'm not aware of here.

提交回复
热议问题