一. 构造函数
- 派生类的构造函数必须调用基类的构造函数初始化基类的那部分成员。如果基类没有默认的构造函数,派生类必须在初始化列表阶段调用基类的构造
- 派⽣类对象初始化先调用基类构造再调派生类构造。
class Person
{
public:
Person(string name)
{}
};
class Student : public Person
{
public:
Student()
:Person("zhang")
{}
};
二. 拷贝构造函数
- 派⽣类的拷贝构造函数必须调⽤基类的拷贝构造完成基类的拷贝初始化。
ps:涉及基类和派生类的转换,派生类赋值给基类——>>基类和派生类的转换
class Person
{
public:
Person(string name)
{}
Person(const Person& p)
{}
};
class Student : public Person
{
public:
Student()
:Person("zhang")
{}
Student(const Student& s)
:Person(s)
{}
};
三. operator=
- 派⽣类的operator=必须要调⽤基类的operator=完成基类的复制。
ps:派⽣类的 operator=隐藏了基类的operator=,所以显示调用基类的operator=,需要指定基类作⽤域
class Person
{
public:
Person(string name)
{}
Person& operator=(const Person& p)
{
return *this;
}
};
class Student : public Person
{
public:
Student()
:Person("zhang")
{}
Student& operator = (const Student& s)
{
if (this != &s)
{
Person::operator =(s);
}
return *this ;
}
};
四. 析构函数
- 派⽣类的析构函数会在被调⽤完成后自动调用基类的析构函数清理基类成员。
- 这样才能保证派生类对象先清理派生类成员再清理基类成员的顺序。
- 析构的重写等知识见多态章节
class Person
{
public:
~Person()
{
cout << "析构基类" << endl;
}
};
class Student : public Person
{
public:
~Student()
{
cout << "析构派生类" << endl;
}
};
int main()
{
Person* per=new Person ;
Student *stu=new Student;
delete stu;
return 0;
}
