Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4272919
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 12:44:05



  1. 初始化方法:
  2. int a=0;   常量定义
  3. int b=a;

  4. CStudent stu1("tom",20);
  5. CStudent stu2;

  1. void main()
  2. {
  3.   CStudent stu1("TOM",88);  构造函数初始化

  4.   CStudent stu2(stu1);     拷贝构造方法
  5. }


拷贝构造方法的定义:

  1. #include<iostream.h>
  2. class CStudent
  3. {
  4.  public:
  5.     CStudent(char *name,int score);
  6.   CStudent(const CStudent &stu);  拷贝构造方法
  7.  private:
  8.     char *m_name;
  9.     int m_score
  10. }

  1. CStudent::CStudent(char *name,int socre)
  2. {
  3.    m_name=name;
  4.    m_score=score;
  5. }


  6. CStudent::CStudent(const CStudent &stu)    拷贝构造方法 定义    const stu1 是常量,不会改变
  7. {
  8.   strcpy(m_name,stu.m_name);  现在 this 指向 stu2 这个对象
  9.   m_age=stu.m_age;
  10. }
const CStudent &stu,为什么要&用引用呢??

假如没有 &,是 const CStudent stu,

那么如果stu1 传值,就要进行数据对象拷贝,数据拷贝就要

调用拷贝构造函数,那么这样如此循环下去,就无法结束了,

所以要进行引用



拷贝构造函数必须要有,如果没有自己定义拷贝构造函数,系

统会提供。


















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