C朋友班
发布时间:2020-12-16 03:43:58 所属栏目:百科 来源:网络整理
导读:我意识到关于C中的朋友课有很多问题.不过,我的问题与具体情况有关.鉴于以下代码,以这种方式使用朋友是否合适? class Software{ friend class SoftwareProducer; SoftwareProducer* m_producer; int m_key; // Only producers can produce software Software
我意识到关于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这样的“Manager”类,并且只需要在Software中使用静态方法.因为似乎只有一个SoftwareProducer.也许这样的东西: class Software { private: Software() : m_key(0) { /* whatever */ } public: void buy() { m_key = new_key(); } public: static Software *create() { return new Software; } private: static int new_key() { static int example_id = 1; return example_id++; } private: int m_key; }; 然后你可以这样做: Software *soft = Software::create(); soft->buy(); 当然,如果您计划拥有多个SoftwareProducer对象,那么您所做的似乎是合适的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |