问题的提出:编写程序实现对象资源的拷贝(要求使用this指针)。
// test2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Student
{
public:
Student(char * pName="no name", int ssID=0)
{
ID=ssID;
Name=new char[strlen(pName)+1];
strcpy(Name,pName);
cout<<"construct new student "<<pName<<endl;
}
void copy(Student &s)
{
cout<<"construct copy of "<<s.Name<<endl;
strcpy(Name,s.Name);
ID=s.ID;
}
void disp()
{
cout<<"Name: "<<Name<<" ID: "<<ID<<endl;
}
~Student()
{
cout<<"Destruct "<<Name<<endl;
delete Name;
}
private:
int ID;
char *Name;
};
int _tmain(int argc, _TCHAR* argv[])
{
Student a("Kevin",12), b("Tom",23);//构造函数
a.disp();
b.disp();
a.copy(a);
b.copy(a);
a.disp();
b.disp();
system("pause");
return 0;
}