Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1747340
  • 博文数量: 413
  • 博客积分: 8399
  • 博客等级: 中将
  • 技术积分: 4325
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-09 10:44
文章分类

全部博文(413)

文章存档

2015年(1)

2014年(18)

2013年(39)

2012年(163)

2011年(192)

分类: C/C++

2011-09-01 17:58:40

在基类中定义了友元函数,在派生类继承了基类中的友元函数吗?
用例子来说明:
  1. #include <iostream>
  2. using namespace std;
  3. class Increase
  4. {
  5. public:
  6.     Increase(int x):value(x){}

  7.     friend Increase& operator++(Increase&); //前增量
  8.     friend Increase operator++(Increase&, int); //后增量

  9.     void display(){ cout << "the value of Increase is " << value <<endl;}

  10. protected:
  11.     int value;
  12. };

  13. Increase& operator++(Increase& a)
  14. {
  15.     a.value++;
  16.     return a;
  17. }
  18. Increase operator++(Increase& a, int)
  19. {
  20.     Increase temp(a);
  21.     a.value++;
  22.     return temp;
  23. }

  24. class Derived: public Increase
  25. {
  26. public:
  27.     Derived(int x):Increase(x){}
  28. };

  29. int main()
  30. {
  31.     Derived der(10);
  32.     der.display();
  33.     (++der).display();

  34.     return 0;
  35. }
运行的结果为:
the value of Increase is  10
the value of Increase is  11

从这个结果来看:似乎可以得出“派生类继承了基类的友元函数”的结论。但是,我们将代码稍微
修改一下:
  1. #include <iostream>
  2. using namespace std;
  3. class Increase
  4. {
  5. public:
  6.     Increase(int x):value(x){}

  7.     friend Increase& operator++(Increase&); //前增量
  8.     friend Increase operator++(Increase&, int); //后增量

  9.     void display(){ cout << "the value of Increase is " << value <<endl;}

  10. protected:
  11.     int value;
  12. };

  13. Increase& operator++(Increase& a)
  14. {
  15.     a.value++;
  16.     return a;
  17. }
  18. Increase operator++(Increase& a, int)
  19. {
  20.     Increase temp(a);
  21.     a.value++;
  22.     return temp;
  23. }

  24. class Derived: public Increase
  25. {
  26. public:
  27.     Derived(int x):Increase(x){}

  28.     friend Derived& operator++(Derived&); //前增量
  29.     void display(){ cout << "the value of Derived is " << value <<endl; }
  30. };
  31. Derived& operator++(Derived& a)
  32. {
  33.     a.value++;
  34.     a.value++;
  35. }

  36. int main()
  37. {
  38.     Derived der(10);
  39.     der.display();
  40.     (++der).display();

  41.     return 0;
  42. }
运行结果为:
the value of Derived is  10
the value of Derived is  12

可以看出,派生类根本没有继承基类的友元函数,但是我们可以将派生类的对象传递给基类的友元函数,
他会自动转换成基类的对象,使得基类的友元函数也可以调用成功。

阅读(1430) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~