私有内部成员的操作符重载

Operator overloading of private inner members

本文关键字:操作符 重载 成员 内部      更新时间:2023-10-16

是否可以将私有内部类成员重载为非成员?在我看来,唯一的方法就是作为成员重载。

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;
}

我想我可以只使用成员重载,但我理解最好将+操作符重载为非成员,并且我想分开实现。

似乎没有人想要宣称这一点,为了完整起见,我将提供答案。这要归功于juanchopanza和Igor Tandetnik。

解决方案是使用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;
}