在下面的情况下,除了使用 friend 还有其他选择吗?我想保留重载运算符 >> 的所有功能。我不想在读者类中有公共(public)访问器。
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 的多个派生类,因此有多个友元声明。这不是滥用 friend 的概念吗?
最佳答案
我想最好的解决方案取决于 end 与 Reader 的关系。
您是否考虑过使用私有(private)继承(一种接口(interface))的基类?您只会公开您需要的内容,其他人无法访问。举个例子:
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);
}
};
关于c++ - 重载时 friend 的替代>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9813591/