下面的代码显示了一个类,该类从一个接口私有继承,该接口在不授予调用对象友谊的情况下访问其私有函数。我对此感到困惑,但真的看不出编译器能提出什么更好的解决方案(代码编译和运行)。为什么这行得通?
#include <iostream>
class IVisitor;
class IVisitable
{
public:
virtual void Accept(IVisitor& visitor) const = 0;
};
class VisitableA;
class VisitableB;
class IVisitor
{
public:
virtual void Visit(const VisitableA& a) = 0;
virtual void Visit(const VisitableB& b) = 0;
};
class VisitableA : public IVisitable
{
public:
virtual void Accept(IVisitor& visitor) const
{
visitor.Visit(*this);
}
};
class VisitableB : public IVisitable
{
public:
virtual void Accept(IVisitor& visitor) const
{
visitor.Visit(*this);
}
};
class PrivateVisitor : private IVisitor
{
public:
PrivateVisitor(IVisitable& v)
{
v.Accept(*this);
}
private:
virtual void Visit(const VisitableA& a)
{
std::cout << "I saw A\n";
}
virtual void Visit(const VisitableB& b)
{
std::cout << "I saw B\n";
}
};
int main(int argc, char* argv[])
{
VisitableA a;
VisitableB b;
PrivateVisitor p_a(a);
PrivateVisitor p_b(b);
}