Overloading Arithmetic Operators

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

提交回复
热议问题