文档介绍:
#ifndef STUDENT_H
#define STUDENT_H
class Student
{
public:
Student(char* pName="no name",int ssID=0);
Student(Student& s);//拷贝构造函数
~Student();
protected:
char name[40];
int id;
};
#endif
#include <iostream>
#include <string>
#include ""
using namespace std;
Student::Student(char* pName,int ssID)
{
strcpy(name,pName);
cout<<"constructing new student"<<pName<<endl;
}
Student::Student(Student& s)
//拷贝构造函数,必须用引用或指针,不能直接用student(student s)
//因为不能像基本数据类型那样直接传递对象的值。
{
cout<<"constructing copy of"<<<<endl;
strcpy(name,"copy of");
strcat(name,);
id=;
}
Student::~Student()
{
cout<<"destructing"<<name<<endl;
}
/*
*
*堆与拷贝构造函数的测试
*2011/10/7
*刘珅珅
*/
#include <iostream>
#include <string>
#include ""
using namespace std;
void fn(Student s);
int main(int argc,char* argv[])
{
Student randy("Randy",1234);
cout<<"calling fn()\n";
fn(randy);//要调用拷贝构造函数
cout<<"returned from fn()\n";
Student jenny=randy;//调用拷贝构造函数
return 0;
}
void fn(Student s)
{
cout<<"In function fn()\n";
}
输出的结果:
有拷贝构造函数:
constructing new studentRandy
calling fn()
constructing copy of Randy
In functiong fn()
destructingcopy ofRandy//fn()函数结束,发生析构,析构的是fn中s对象
returned from fn()
constructing copy of Randy//拷贝构造jenny对象
destructingcop