Overloading Arithmetic Operators

后端 未结 4 1490
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 10:52

The assignment operator can be declared as

T& operator= (const t&);

in a class, but the arithmetic operators cannot be defined that way. It has to be fri

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-24 11:02

    They ideally should be globals and not necessarily friends, so that you can write:

    yourtype v = 1;
    yourtype w = 1 + v;
    

    Since, 1 is not an object of yourtype, if the operator+ were a member it would throw a fit. However, making it global makes it convert the 1 to yourtype and then perform the operation. Making it a friend helps to extract and manipulate the members of yourtype as required -- though not required. As an example: You can implement the member function operator+= and use it in the implementation of the operator+.

提交回复
热议问题