在下面的情况中,有没有替代使用朋友?我想保留运算符重载的所有功能>>。我不想在读者类中使用公共访问器。
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派生类,因此有多个朋友声明。这不是滥用朋友的概念吗?答案 0 :(得分:2)
我认为最佳解决方案取决于结束与读者的关系。
您是否考虑过具有私有继承的基类(接口类型)?您只会公开您需要的内容,而其他人无法访问。就像例子一样:
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);
}
};