既然我已经说了我关于继承的文章,这里有一些可能有助于解决你真正的问题,即如何解决友谊的潜在问题。
我这样做的方法是创建一个纯界面来访问我想与我的“朋友”分享的数据。然后我私下实现这个接口,所以没有人可以直接访问它。最后,我有一些机制允许我将接口的引用仅传递给那些我想要允许的选择类。
例如:
// This class defines an interface that allows selected classes to
// manipulate otherwise private data.
class SharedData
{
public:
// Set some shared data.
virtual void SettorA(int value) = 0;
// Get some shared data.
virtual bool GettorB(void) const;
};
// This class does something with the otherwise private data.
class Worker
{
public:
void DoSomething(SharedData & data)
{
if (data.GettorB() == true)
{
data.SettorA(m_id);
}
}
private:
int m_id;
};
// This class provides access to its otherwise private data to
// specifically selected classes. In this example the classes
// are selected through a call to the Dispatch method, but there
// are other ways this selection can be made without using the
// friend keyword.
class Dispatcher
: private SharedData
{
public:
// Get the worker to do something with the otherwise private data.
void Dispatch(Worker & worker)
{
worker.DoSomething(*this);
}
private:
// Set some shared data.
virtual void SettorA(int value)
{
m_A = value;
}
// Get some shared data.
virtual bool GettorB(void) const
{
return (m_B);
}
int m_A;
bool m_B;
};
在这个例子中,SharedData 是一个接口,它决定了可以对数据做什么,即可以设置什么,什么是只能获取的。Worker 是一个允许访问这个特殊接口的类。Dispatcher 以私有方式实现接口,因此访问 Dispatcher 实例不会让您访问特殊的共享数据,但 Dispatcher 有一个方法可以让 Workers 获得访问权限。