Person 类的定义
class Person
{
char Name[9];
char Sex;
int Age;
public:
Person( ) // 构造函数
{
strcpy(Name,"XXX");
Age = 0;
Sex = ' ';
}
~Person( ) // 析构函数
{
cout<<"Now destroying Person"<<endl; }
void Register(char *name, int age, char sex);
void ShowMe( );
};
类外定义函数
void Person::Register(char *name, int age, char sex)
{
strcpy(Name,name);
Age = age;
Sex = sex;
}
void Person::ShowMe()
{
cout<<Name<<'\t'<<Age<<'\t'<<Sex<<endl;
}
Person 类函数测试主函数
int main()
{
Person person1, person2;
cout<<"person1:\t";
person1.ShowMe();
person1.Register("zhang3",19,'m');
cout<<"person1:\t";
person1.ShowMe();
cout<<"person2:\t";
person2.ShowMe();
person2=person1;
cout<<"person2:\t";
person2.ShowMe();
return 0;
}
完善Person类
完善person类的定义
- 增加身份证号码,可以定长
char Pid[19];
- 增加住址,住址数据无法定长度,就是字符指针
Person类的数据成员定义如下:
class Person
{
private:
char Name[9];
char Sex;
int Age;
char Pid[19];
char *Addr;
public:
……
}
实现
class Person
{
char Name[9];
char Sex;
int Age;
char Pid[19];
char *Addr;
public:
Person()
{
strcpy(Name, "xxxxxxxx");
Age = 0;
Sex = 'x';
strcpy(Pid, "xxxxxxxxxxxxxxxxxx");
Addr=NULL;
}
Person(char *N, int A, char S,char *P,char *Ad)
{
strcpy(Name,N);
Age = A;
Sex = S;
strcpy(Pid,P);
int L=strlen(Ad);
Addr=new char[L+1];
strcpy(Addr,Ad);
}
~Person( )
{
cout<<"Now destroying Person"<<Name<<endl;
delete [ ] Addr;
}
void Register( char *name, int age, char sex,char *pid,char *addr);
void ShowMe( );
};
类外定义成员函数
void Person::Register(char *name,int age,char sex,char *pid,char *addr)
{
strcpy(Name,name);
Age = age;
Sex = sex;
strcpy(Pid, pid);
if(Addr!=NULL)
delete [ ] Addr;
int L=strlen(addr);
Addr = new char[L+1];
strcpy(Addr,addr);
}
void Person::ShowMe()
{
cout << Name << " " << Age << " " << Sex << " " << Pid << " ";
if(Addr != NULL) // 需要判断是否为空指针
cout<<Addr;
cout << endl;
}
测试主函数
int main()
{
Person person1;
Person person2("张三",19,'m',"610103199409192839","中国西安市咸宁西路29号");
Person person3;
cout<<"person1: ";
person1.ShowMe();
cout<<"person2: ";
person2.ShowMe();
person3.Register("李四",29,'w',"610103198409192493","中国上海市华山北路1845号");
cout<<"person3: ";
person3.ShowMe();
person2.Register("赵五",29,'w',"610103198409152127","中国新疆乌鲁木齐市王家沟12号");
cout<<"person2: ";
person2.ShowMe();
return 0;
}
可以看见析构函数作用了,先删除Person3->Person2->Person1