are friend function a good practice in this case>?

Viewed 41

I have a few questions about good practices, I have this piece of code in c++:

class Complex{
        friend double Re(Complex &z);
        friend double Im(Complex &z);
        friend Complex operator + (Complex &augend, Complex &adend);
        friend Complex operator - (Complex &minuend, Complex &substraend);
        friend Complex operator * (Complex &multiplier, Complex &multiplicand);
    public:
        Complex &operator = (Complex &z); 
        Complex(double real, double imaginary);
        void print(void);
    private:
        double real, imaginary;
};

With functions like:

double Re(Complex &z){
    return z.real;
}

With some operators overloaded like:

Complex operator + (Complex &z, Complex &w){
    return Complex(
        z.real + w.real,
        z.imaginary + w.imaginary);

}

If I can get the real and imaginary private variables using Re() and Im() functions that return them, should I use friend functions that use private variables, or should I write the operators in terms of these functions, something like

Complex operator + (Complex &z, Complex &w){
        return Complex(
            Re(z) + Re(w),
            Im(z) + Im(w));
    }

Also, is there a point in making real, and imaginary variables private if I'm gonna use them outside class anyway with those functions?

Another question, I don't see the propourse in overload = operator like this:

Complex& Complex::operator = (Complex &z){
    this->real = z.real;
    this->imaginary = z.imaginary;
    return *this;
}

If I don't do it, I can do something like Complex C = A + B with A and B complex clases, in the main anyway.

And last question, what is the best practice? To declare functions with variables like this?:

friend Complex operator + (Complex &augend, Complex &adend);

or should I declare without them like this?:

friend Complex operator + (Complex &, Complex &);

?

0 Answers
Related