Difference between operator and function in C++?

后端 未结 8 502
夕颜
夕颜 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.

    0 讨论(0)
  • 2021-02-01 09:04

    In C++ you can override what the symbols +, -, ==, etc. do when applied to class instances. By defining the "operator+" method in class A, you are telling the compiler what to do with code like:

    A a, b, c;
    c = a + b; // the + here actually calls a.operator+(b)
    

    It's also a function or more precisely an instance method, in the sense that it's something that gets called.

    EDIT: see also http://en.wikipedia.org/wiki/Operator_overloading and http://en.wikibooks.org/wiki/C++_Programming/Operators/Operator_Overloading

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