Overloading Arithmetic Operators

后端 未结 4 1448
爱一瞬间的悲伤
爱一瞬间的悲伤 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 10:59

    It is not mandatory that arithmetic operators should be friend

    Well you can define like this:

    MyClass MyClass::operator + (const MyClass& t) const
    {
      MyClass ret(*this);
      ret += t;
      return ret;
    }
    

    The a + b is really a syntax sugar, the compiler will expand it to a.operator+(b). The previous sample will work if all your objects are MyClass instances, but will not work if you have to operate with others types, ie 1 + a, will not work, this can be solved by using friends.

    MyClass operator + (int i, const MyClass& t)
    {
      MyClass ret(i);
      ret += t;
      return ret;
    }
    

    This has to be done when the left hand side of the + operator is not a class, or it is a class but you can't add operator + to its definition.

    0 讨论(0)
  • 2021-01-24 10:59

    I think that C++ FAQ Lite will give you a definitive answer.

    0 讨论(0)
  • 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+.

    0 讨论(0)
  • 2021-01-24 11:20

    The problem is that if you do something like this:

    class A
    {
        A& operator+(int n);
        // ...
    }
    
    int main()
    {
        A my_var;
        int integer = 1;
        A + integer; // compiles
        integer + A // error: no function operator+(int, A) defined
    }
    

    it will not compile. A solution is to define operator+(int, A) and operator+(A, int) as friends of A. As a side note, the Boost Operators library makes this process very easy.

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