我意識到有很多關於C++中的朋友類的問題。然而,我的問題與特定情況有關。鑑於下面的代碼,以這種方式使用朋友是否合適?C++朋友類
class Software
{
friend class SoftwareProducer;
SoftwareProducer* m_producer;
int m_key;
// Only producers can produce software
Software(SoftwareProducer* producer) : m_producer(producer) { }
public:
void buy()
{
m_key = m_producer->next_key();
}
};
class SoftwareProducer
{
friend class Software;
public:
Software* produce()
{
return new Software(this);
}
private:
// Only software from this producer can get a valid key for registration
int next_key()
{
return ...;
}
};
感謝,
最好的問候,
我使Software成爲SoftwareProducer的一位朋友,以便訪問私有的next_key方法。 – Alex 2009-04-18 07:29:46
這不是相反嗎?爲了允許從SoftwareProducer調用Software的私有構造函數,您需要使SoftwareProducer成爲Software的一位朋友,正如我所說的那樣。但是你也使軟件成爲SoftwateProducer的一個朋友,所以可以調用next_key()方法,我覺得這是不必要的。 – Naveen 2009-04-18 07:32:00