3742 - C++作业6章指针:动态生成Person类的对象
编写Person类,数据成员为姓名(20字符长度)、年龄(int)和性别(char)。
编写无参数的构造函数,其中姓名赋值为“XXX”,年龄0,性别m;
编写析构函数,在其中输出字符串“Now
destroying the instance of
Person”;
编写Register成员函数,为数据成员赋值;
编写showme成员函数,显示姓名、年龄和性别。
编写主函数:
用Person类创建2个指针,p1和
p2;
用new创建两个Person对象,分别将指针赋值给p1,p2;
用showme成员函数显示p1,p2所指对象的值;
再输入一组“姓名、年龄和性别”值,用成员函数Register为p1的成员赋值;
将p1所指对象的值赋值给p2所指对象;
用showme显示p1、p2所指对象的值。
删除动态对象。
Input
为p1的成员赋值时使用的数据
Output
person1和person2的默认值
person1和person2的赋值后的值
析构函数输出的信息
Examples
Input
Bobs 24 m
Output
person1:XXX 0 m person2:XXX 0 m person1:Bobs 24 m person2:Bobs 24 m Now destroying the instance of Person Now destroying the instance of Person
Hint
动态存储分配,要使用new和delete;
Solution C++
#include <iostream> #include <string.h> using namespace std; class Person{ public: Person(); void Register();//成员 赋值函数 void showme(); ~Person(); private: char name[20]; int age; char x; }; Person::Person(){ char w[20]="XXX"; int a=0; char c='m'; strcpy(name,w); age=a; x=c; } void Person::Register(){ cin>>name; cin>>age; cin>>x; } void Person::showme(){ cout<<name<<" "<<age<<" "<<x<<endl; } Person::~Person(){ cout<<"Now destroying the instance of Person"<<endl; } int main(){ int i; Person s[2]; Person *p1,*p2; p1=&s[0]; p2=&s[1]; s[0].Register(); for(i=0;i<2;i++){ cout<<"person"<<i+1<<":"; s[1].showme(); } s[1]=s[0]; cout<<"person"<<1<<":"; p1->showme(); cout<<"person"<<2<<":"; p2->showme(); return 0; }
Hint
动态存储分配,要使用new和delete;