免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 11166 | 回复: 3

[函数] 在派生类中怎么调用基类的 拷贝构造函数 和 赋值函数 ? [复制链接]

论坛徽章:
0
发表于 2007-10-06 22:08 |显示全部楼层
2可用积分
看到这么一个结论:
---------------------
1> 要在派生类 拷贝构造函数 中调用 基类 的 拷贝构造函数!
2> 要在派生类 赋值函数     中调用 基类 的 赋值函数!

问题:
    在派生中调用基类的构造函数这样写就可以了
    派生类(总参数表) : 基类(基类参数表)
    {
           ... ;
      }

      1> 和 2> 应该怎么写,个人想了半天不知道怎么写,请大家写个简单的例子,谢了!

最佳答案

查看完整内容

不知可否?[ 本帖最后由 sanbiangongzi 于 2007-10-7 10:19 编辑 ]

论坛徽章:
0
发表于 2007-10-06 22:08 |显示全部楼层
不知可否?

  1. #include <iostream>
  2. using namespace std;

  3. class base
  4. {
  5. public:
  6.     base(){_a=0;}
  7.     base(const base & obj){
  8.         _a=1;
  9.         cout<<"base copy constructor"<<endl;
  10.     }
  11.     base & operator=(const base & obj){
  12.         _a=2;
  13.         cout<<"base operator="<<endl;
  14.     }
  15.     int _a;
  16. };

  17. class derive : public base
  18. {
  19. public:
  20.     derive(){_b=0;}
  21.     derive(const derive & obj):base(obj){
  22.         _b=1;
  23.         cout<<"derive copy constructor"<<endl;
  24.     }
  25.     derive & operator=(const derive & obj){
  26.         base::operator=(obj);
  27.         _b=2;
  28.         cout<<"derive operator="<<endl;
  29.     }
  30.     int _b;
  31. };

  32. int main(int argc, char *argv[])
  33. {
  34.     derive d1;
  35.     derive d3 = d1;
  36.     cout<<d3._a<<" "<<d3._b<<endl;
  37.     d3 = d1;
  38.     cout<<d3._a<<" "<<d3._b<<endl;

  39.     return 0;
  40. }

复制代码

[ 本帖最后由 sanbiangongzi 于 2007-10-7 10:19 编辑 ]

论坛徽章:
0
发表于 2007-10-06 22:11 |显示全部楼层
看书吧,书中自有黄金屋

论坛徽章:
0
发表于 2007-10-08 18:30 |显示全部楼层
授人于鱼, 不如授人于渔...

effectiveC++.chm

459.18 KB, 下载次数: 7086

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP