1
votes

I'm confused about friend operator overloading. It has no problem if I write the friend operator overloading function within the header file, but it gives me the following errors once I moved the function to class file. I googled some samples and they all written the function in the header file. What did I do wrong? Thanks.

...: error: expected ‘,’ or ‘...’ before ‘&’ token
...: error: ISO C++ forbids declaration of ‘statisticain’ with no type
...: error: ‘main_savitch_2C::statistician operator+(int)’ must have an argument of class or enumerated type


// a.h
class A
{
    public:
        friend A operator + (const A &a1, const A &a2);
};

// a.cpp
#include "a.h"
A operator + (const A &a1, const A &a2)
{
    //
}
3
That code works fine for me. What does your actual code look like? - Adam Rosenfield
Since everybody is giving advice on how to overload operator+ correctly, here's my advice. - Benjamin Lindley

3 Answers

3
votes

From the error message you're getting:

ISO C++ forbids declaration of ‘statisticain’ with no type

I think that you misspelled "statistician" by reversing the last two letters (note that you have "statisticain" instead of "statistician.")

This should have nothing to do with whether operator+ is implemented in the header or the .cpp file.

1
votes

I agree with the previous answer. Also, if I may ask, why make the function a friend when both arguments and the return type are of the same class? why not make it a member so the first argument is passed implicitly by the this operator?

0
votes

Move the two param version out of the class declaration. Or just use one param and the this pointer.

Here's an abbreviated real world example.

//complexnumber.h 
    class ComplexNumber
    {
        float _r;
        float _i;

        friend ComplexNumber operator+(const ComplexNumber&, const ComplexNumber&);

        public:
            ComplexNumber(float real, float img):_r(real),_i(img) {}
            ComplexNumber& operator + (const ComplexNumber &other);
    };

    ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2);


//complexnumber.h 
    ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2)
    {
        return ComplexNumber(c1._r+c2._r, c1._i+c2._i);
    }


    // static
    ComplexNumber& ComplexNumber::operator + (const ComplexNumber &other)
    {
        this->_r = this->_r + other._r;
        this->_i = this->_i + other._i;

        return *this;

    }