Operator overloading with private internal members

Is it possible to overload a private inner member of a class as a non-member? It seems to me that the only way is to overload as a member.

class Foo
{
private:
    struct Bar
    {
        int a;
        char b;

        Bar& operator+=(const Bar& rhs)
        {
            a += rhs.a;
            return *this;
        }

        // Only possibility?
        inline Bar operator+(const Bar& rhs)
        {
            Bar bar;
            bar.a = this->a + rhs.a;
            bar.b = this->b;
            return bar;
        }
    };

    // Cannot do this as takes implicit reference (to Foo?).
    inline Bar operator+(Bar lhs, const Bar& rhs)
    {
        lhs += rhs;
        return lhs;
    }
};

// Cannot do this as Bar private.
inline Foo::Bar operator+(Foo::Bar lhs, const Foo::Bar& rhs)
{
    lhs += rhs;
    return lhs;
}

      

I think I could just use element overloading, but I understand that it is preferable to overload the operator +

as a non-member and I would like to separate the implementation.

+3


source to share


1 answer


It does not seem like anyone wants to state this, I will give an answer for completeness. The loan goes to juanchopanza and Igor Tandetnik.

The solution is to use friend

.



class Foo
{
private:
    struct Bar
    {
        int a;
        char b;

        Bar& operator+=(const Bar& rhs)
        {
            a += rhs.a;
            return *this;
        }
    };
    friend Bar operator+(Bar, const Bar&);
};

Foo::Bar operator+(Foo::Bar lhs, const Foo::Bar& rhs)
{
    lhs += rhs;
    return lhs;
}

      

+1


source







All Articles