Reputation: 8431
Is it possible to overload a private inner class member as a non-member? It seems to me 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 guess I could just use the member overload, but I understand it's preferable to overload the +
operator as a non-member, and I would like to separate the implementation.
Upvotes: 3
Views: 339
Reputation: 8431
Doesn't look like anyone wants to claim this, I'll provide the answer for completeness. Credit 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;
}
Upvotes: 2