C++学习笔记——构造函数与析构函数

构造函数的功能是初始化数据,析构函数的功能是在撤销对象之前进行一些善后处理工作

#include
#include
using namespace std;
class Person{
     
	private:
		char Name[9];
		int Age;
		char Sex;
	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;
}
int main(){
     
	Person *p1,*p2;
	p1=new Person;
	p1->ShowMe();
	p1->Register("wang",22,'m');
	p1->ShowMe();
	p2=new Person;
	p2->ShowMe();
	*p2=*p1;
	p2->ShowMe();
	delete p1;
	delete p2;
	return 0;
}

运行结果:
XXX 0
wang 22 m
XXX 0
wang 22 m
Now destroying Person
Now destroying Person

你可能感兴趣的:(C++学习笔记,c++)