cat person.cpp
#include <iostream>
#include <cstring>
using namespace std;
class Person {
public:
//无参构造函数
Person();
// 有参构造函数
Person(int myage, const char *myname);
//析构函数
~Person();
//拷贝构造函数
Person(const Person& b);
//赋值函数
Person& operator=(const Person& b);
//普通成员函数
void display();
private:
int age;
char *name;
};
Person::Person()
:age(10),name(NULL)
{
cout << "Person::Person() 无参构造函数被调用 " << endl;
//age = 10;
name = new char[20];
strcpy(name, "XiaoMing");
}
Person::Person(int age, const char *name)
{
cout << "Person::Person(int, const char*) 有参构造函数被调用 " << endl;
this->age = age;
this->name = new char[strlen(name)+1];
strcpy(this->name, name);
}
#if 1
/**
* 等号运算符重载
*/
Person& Person::operator=(const Person& b)
{
cout<<"Person::operator() 赋值函数被调用 "<<endl;
if(this == &b)
return *this;
this->age = b.age;
delete[] name;
this->name = new char[strlen(b.name)+1];
strcpy(this->name, b.name);
return *this;
}
#endif
Person::Person(const Person& b)
{
cout << "Person::Person(const Person&) 拷贝函数被调用" << endl;
this->age = b.age;
//delete[] name;//这个是构造函数在初始化,这之前对象还未存在
this->name = new char[strlen(b.name)+1];
strcpy(this->name, b.name);
//return *this;//构造函数没有返回值
}
Person::~Person(void)
{
cout << "Person::~Person() 虚构函数被调用 " << endl;
delete[] name;
}
void Person::display()
{
cout << "数据显示:Name:" << name << ", Age:" << age << endl;
return;
}
int main()
{
#if 0
Person a; //Person::Person()
a.display();
#endif
#if 0
Person b(20, "XiaoLi"); //Person::Person(int, char*)
b.display();
#endif
#if 0
// 调用等号运算符重载函数
a = b;//赋值 调用了operator=(...)赋值函数
a.display();
#endif
#if 0
cout << "=====" << endl;
Person c = b; //不是赋值,是初始化,调用了拷贝构造函数,而不是赋值函数
c.display();
//Person d = d; //这种不可能,因为d还不存在
#endif
#if 0
/* 调用参构造 */
Person *pa = new Person;
pa->display();
delete pa;
#endif
#if 0
Person *pb = new Person(20, "XiaoLi");
pb->display();
delete pb;
#endif
return 0;
}