Chinaunix首页 | 论坛 | 博客
  • 博客访问: 473921
  • 博文数量: 120
  • 博客积分: 1853
  • 博客等级: 上尉
  • 技术积分: 1177
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-22 22:40
文章分类

全部博文(120)

文章存档

2013年(16)

2012年(104)

分类: C/C++

2012-06-09 23:42:28

复制构造函数,必须显式的定义每一个需要复制的变量,如果没有显式指定的话,就会使用合成默认构造函数的方式处理。

点击(此处)折叠或打开

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

  4. class test{
  5. public:
  6.     test(){                       //使用复制构造函数,但是如果没在复制构造函数中定义的呢?定义了默认构造函数,根据结果,发现没有调用。说明只是调用了类本身的构造函数。在这里是string类
  7.         num = 1;
  8.         str = "unix";
  9.     }
  10.     test(int num, string sq):num(num), str(sq) {};
  11.     test(const test &m): num(m.num){}; //若加上str(m.str)就可以正常了。
  12.     void show(){
  13.         cout<<"str "<<str<<" num "<<num<<endl;
  14.     }
  15. private:
  16.     string str;
  17.     int     num;
  18. };


  19. int main(){

  20.     class test tes1(1,"china");
  21.     class test tes2(tes1);
  22.     tes2.show();

  23.     return 0;
  24. }
显示的结果是
str num 1 而不是str china num 1
如果改变复制构造函数就可以有china了
阅读(538) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~