継承に関する私の記事を述べたので、ここであなたの本当の質問、つまり友情に関する潜在的な問題を回避する方法を助けるかもしれないものがあります.
これを行う方法は、「友達」と共有したいデータにアクセスするための純粋なインターフェイスを作成することです。次に、このインターフェイスをプライベートに実装して、誰も直接アクセスできないようにします。最後に、インターフェイスへの参照を、許可したい選択クラスにのみ渡すことができるメカニズムがあります。
例えば:
// 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 にはワーカーがアクセスできるメソッドがあります。