Functions with return values (C++)

前端 未结 6 1112
南旧
南旧 2020-12-11 23:10

When main() calls a function which has a return value of some datatype ( primitive or user-defined ) , the statement in which the function is called is \'usually\' an assign

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 23:43

    Another solution is to use operator + in global scope but as a friend of your class:

    class complex
    {
        // ...
    
    public:
    
        // ...
    
        friend complex operator +(const complex &c1, const complex &c2)
        {
            complex c;
            c.real = c1.real + c2.real;
            c.imag = c1.imag + c2.imag;
            return c;
        }
    
        // ...
    
    };
    

    Using this technique you can also use an integer as argument (at the lhs) by adding:

        friend complex operator +(const int n, const complex &c)
        {
            complex c;
            c.real = n + c.real;
            c.imag = c.imag;
            return c;
        }
    
        friend complex operator +(const complex &c, const int n)
        {
            complex c;
            c.real = c.real + n;
            c.imag = c.imag;
            return c;
        }
    

    So now you can also do

     complex c1, c2, c3;
     c3 = 1 + c2 + 8 + c1 + 2;
    

    and your class is missing a (virtual) destructor, I would also make the member variables protected instead of private :)

提交回复
热议问题