设为首页 加入收藏

TOP

9.5 友元类成员
2013-10-07 12:39:02 来源: 作者: 【 】 浏览:59
Tags:9.5 元类 成员

9.5  友元类成员

我们在第7章学过将函数声明为类友元的方法,友元函数有权自由访问任何类成员。当然,我们没有理由说友元函数不能是另一个类的成员。

假设我们定义了一个表示瓶子的CBottle类:

  1. class CBottle  
  2. {  
  3. public:  
  4. CBottle(double height, double diameter)  
  5. {  
  6. m_Height = height;  
  7. m_Diameter = diameter;  
  8. }  
  9.  
  10. private:  
  11. double m_Height;        // Bottle height  
  12. double m_Diameter;  // Bottle diameter  
  13. }; 

现在,我们需要有一个类来表示一打瓶子的包装箱,该类应该自动具有可容纳特定种类瓶子的定制尺寸。我们可能像下面这样进行定义:

  1. class CCarton  
  2. {  
  3. public:  
  4. CCarton(const CBottle& aBottle)  
  5. {  
  6. m_Height = aBottle.m_Height; // Bottle height  
  7. m_Length = 4.0*aBottle.m_Diameter;  // Four rows of ...  
  8. m_Width = 3.0*aBottle.m_Diameter;       // ...three bottles  
  9. }  
  10.  
  11. private:  
  12. double m_Length;        // Carton length  
  13. double m_Width; // Carton width  
  14. double m_Height;        // Carton height  
  15. }; 

这里的构造函数将包装箱的高度设定为与瓶子相同的高度,基于瓶子的直径将长度和宽度设定为刚好可以容纳12个瓶子。

我们现在知道,这样的定义不能工作。CBottle类的数据成员是private,因此CCarton类的构造函数不能访问它们。我们还知道,在CBottle类中使用friend声明可以修正该问题:

  1. class CBottle  
  2. {  
  3. public:  
  4. CBottle(double height, double diameter)  
  5. {  
  6. m_Height = height;  
  7. m_Diameter = diameter;  
  8. }  
  9.  
  10. private:  
  11. double m_Height; // Bottle height  
  12. double m_Diameter;      // Bottle diameter  
  13. // Let the carton constructor in  
  14. friend CCarton::CCarton(const CBottle& aBottle);  
  15. }; 

这里的friend声明与第7章所介绍的friend声明之间的唯一区别是,我们为了识别友元函数而必须在其名称前面添加类名和作用域解析运算符。为了正确编译这条语句,编译器需要获得有关CCarton类构造函数的信息,因此我们需要在CBottle类的定义之前,添加一条#include语句以嵌入包含CCarton类定义的头文件。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇9.2.1 基类的概念 下一篇9.6.4 纯虚函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: