Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4566342
  • 博文数量: 385
  • 博客积分: 21208
  • 博客等级: 上将
  • 技术积分: 4393
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-30 13:40
文章分类

全部博文(385)

文章存档

2015年(1)

2014年(3)

2012年(16)

2011年(42)

2010年(1)

2009年(2)

2008年(34)

2007年(188)

2006年(110)

分类: C/C++

2006-10-12 15:32:56

 
Student s1("Jenny");
Student  s2=s1;
对象作为函数参数传递时,也要涉及对象的拷贝
void   fn(Student  fs)
{
    //...
}

int main()
{
 Student  ms;
 fn(ms); 
}
函数fn的参数传递方式是传值,参数类型是Student,调用时,实参ms传给了形参fs,ms在传递
的过程中是不会改变的,形参fs是ms的一个拷贝,这一切是在调用的开始完成的,也就是说,形参
fs用ms的值进行构造。
这时候调用构造函数Student(char*)就不合适,新的构造函数的参数应是Student&,也就是:
Student (Student &s);
为什么C++要用上面的拷贝构造函数,而他自己不会作像下面的事呢?
int  a=5;
int  b=a;
因为对象的类型多种多样,不像基本数据类型这么简单,有些对象还申请了系统资源,如s对象拥有了一个资源,用s 的值创建一个t对象,如果仅仅只是二进制内存空间上的s拷贝,那意味着t也拥有这个资源
,由于资源归属权不清,将引起资源管理的混乱。
 
#include
using namespace  std;

class   Student
{
 public:
  Student (char *pName="no name",int ssId=0);
  Student (Student &s);
  ~Student ();
  
 protected :
  char name[40];
  int  id;
};
 Student:: Student (char *pName,int ssId)
{
   id=ssId;
   strcpy(name,pName);
   cout<<"Constructing  new  student"<}
 Student::Student (Student &s)
 {
  cout <<"Constructing copy of "<  strcpy(name,"copy of ");
  strcat(name, s.name);
  id=s.id;
 
 }
 Student::~Student ()
{
   cout <<"Destructing "<}
void fn(Student s)
{
 cout<<"In  function  fn()\n";
}
int main()
{
 Student randy("Randy",1234);
 cout<<"Calling fn()\n";
 fn(randy);
 cout<<"Returned from  fn()\n";
}
 
 
 
阅读(2020) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~