C++ 当超载时,朋友的另一种选择>>;?

C++ 当超载时,朋友的另一种选择>>;?,c++,overloading,friend,functor,C++,Overloading,Friend,Functor,在下面的情况下,除了使用friend,还有其他选择吗?我想保留重载操作符>>的所有功能。我不想在reader类中有公共访问器 struct FunctorBase { virtual ~FunctorBase(){} virtual void operator()(Reader &reader) const = 0; }; //does specific stuff related to the purpose of end. struct end : FunctorB

在下面的情况下,除了使用friend,还有其他选择吗?我想保留重载操作符>>的所有功能。我不想在reader类中有公共访问器

struct FunctorBase
{
    virtual ~FunctorBase(){}
    virtual void operator()(Reader &reader) const = 0;
};

//does specific stuff related to the purpose of end.
struct end : FunctorBase
{
    void operator()(Reader &reader) const
    {
        //work with private data in reader
    }
};

class Reader
{
    friend class end; //I want to get rid of this if possible without losing the
                      //functionality of operator>> or providing accessors

    Reader& operator>>(const FunctorBase &functor)
    {
        functor(*this);

        return *this;
    }
};
感谢您的帮助


编辑:我计划拥有多个FunctorBase派生类,因此有多个友元声明。这不是滥用了朋友的概念吗?

我想最好的解决方案取决于endReader的关系

您是否考虑过使用私有继承的基类(一种接口)?你只会暴露你所需要的,而别人是不会接受的。举个例子:

class ReaderInterface
{
public:
    void method()
    {
    }
};

// This is your "end" class, derived from FunctorBase,
// the consumer of ReaderInterface
class Consumer
{
public:
    Consumer(ReaderInterface readerInterface)
    {
        readerInterface.method();
    }
};

class Reader : private ReaderInterface
{
public:
    void test()
    {
        Consumer consumer(*this);
    }
};

我一直被教导,私有继承是错误的——但在这种情况下,它与朋友声明没有任何区别。即使我使用函数指针而不是运算符()重载的结构,它们仍然必须声明为friend,例如在使用iostream时。所以我想我会坚持使用friend声明,它们都是类的“实现细节”,但我同意私有继承并不常见,不应该被滥用。至少你可以决定你想让什么可见,朋友可以看到一切。这是真的。作为另一种选择,我可以为每个结构定义一个操作符>>重载,但这会破坏所使用的多态性和继承的美观。