Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7549342
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: C/C++

2011-03-29 09:31:23

  1. /***********************************************
  2. * 文件名:例六
  3. * 功能:类的嵌套
  4. * 说明:当数据成员的类型是另外一个已知类时
  5. * 时间:2011-3-29 --Lzy
  6. /***********************************************/
  7. #include <iostream.h>

  8. class ClassA
  9. {
  10. public:
  11.     int x;
  12.     ClassA(int xx)
  13.     {
  14.         cout<<"A is called"<<endl;
  15.         x = xx;
  16.     }
  17. };

  18. class ClassB
  19. {
  20. public:
  21.     ClassB();
  22.     ClassB(int, int);
  23.     void printf();

  24. private:
  25.     ClassA a;        //声明ClassA a对象为自己的私有成员

  26.     int b;
  27. };

  28. ClassB::ClassB():a(99)    //必须使用初始化式调用成员类的构造函数

  29. {
  30.         cout<<"B1 is called"<<endl;
  31.         b = 100;
  32. }

  33. ClassB::ClassB(int x, int y):a(x), b(y)    
  34. {
  35.         cout<<"B2 is called"<<endl;    
  36. }

  37. void ClassB::printf()
  38. {
  39.     cout<<"a="<<a.x<<" b="<<b<<endl;
  40. }

  41. void main()
  42. {
  43.     ClassB b1, b2(200, 220);
  44.     b1.printf();
  45.     b2.printf();
  46. }
阅读(1197) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~