Chinaunix首页 | 论坛 | 博客
  • 博客访问: 544706
  • 博文数量: 104
  • 博客积分: 2089
  • 博客等级: 大尉
  • 技术积分: 1691
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-29 08:48
文章分类

全部博文(104)

文章存档

2015年(1)

2013年(13)

2012年(31)

2011年(59)

分类: C/C++

2011-12-15 16:01:52

友元用于突破protected 或者 private 保护的限制,首先要做的是在被访问者的类中声明是友元函数或者友元类。代码如下
  1. #include <iostream>
  2. using namespace std;

  3. class Square{
  4.         private:
  5.                 int side;
  6.         public:
  7.                 Square(int a):side(a){}
  8.         friend class Rectangle ; //declare the Class is friend


  9. };

  10. class Rectangle {
  11.         private:
  12.                 int width, height;
  13.         public:
  14.                 Rectangle(int a, int b):width(a),height(b){}
  15.                 void set_values (int a, int b){
  16.                         width = a;
  17.                         height = b;
  18.                 }
  19.                 int girth();
  20.                 friend int area (Rectangle &); //declare the friend function here
  21.                 int get_width(){return width;}
  22.                 int get_height(){return height;}
  23.                 void conver_from_square(Square &s){
  24.                         width = height = s.side; //access so easily
  25.                 }
  26. };

  27. //implement the function here , access easily ,too
  28. int area (Rectangle &r){ return ( r.width * r.height); }
  29. int r_area(Rectangle &r){ return r.get_width() * r.get_height();}
  30. int Rectangle::girth(){return width + width + height + height; }

  31. int main () {
  32. test_sizeof:
  33.         cout << "sizeof: Square " << sizeof(Square)
  34.              << ",\tRectangle " << sizeof(Rectangle) << "\n\n" ;
  35. test_access:
  36.         Rectangle r(2,3);
  37.         cout << "area:" << area(r) << "\tgirth:" << r.girth() << endl;
  38.         cout << "onather way:area " << r_area(r) << endl;

  39.         Rectangle r1(2,3);
  40.         Square s(5);
  41.         r1.conver_from_square(s);
  42.         cout << "rectangle convering from square , girth is " << r1.girth() << endl;
  43.         return 0;
  44. }
结果
  1. sizeof: Square 4, Rectangle 8
  2. area:6 girth:10
  3. onather way:area 6
  4. rectangle convering from square , girth is 20
看函数
  • area
  • r_area
  • girth
如果不是友元函数或类,访问情况如 r_area()函数,友元函数就可以直接访问成员。但是和成员函数比起来还是要有区别的,看函数girth()

看看size,友元类或者友元函数并不增加类的大小,只是声明一下。

参考
  1. Friendship and inheritance %20%20/inheritance/
阅读(548) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~