46、继承中的构造与析构

子类中可以定义构造函数:必须对继承而来的成员进行初始化,直接通过初始化列表或者赋值的方式进行初始化(父类private成员行不通)。调用父类构造函数进行初始化。

父类构造函数在子类中的调用方式:默认调用,适用于无参构造函数和使用默认参数的构造函数。

显示调用:通过初始化列表进行调用,适用于所有父类构造函数。

class child:public parent

{

 public:

    child()              //隐式调用父类无参数构造函数

        {

                 cout<<"child "<<endl;                  

         }

        child(string s)  : parent("parameter to parent")    //显示调用父类构造函数

            {

                cout<<"child():"<<s<<endl;

            }

};

#include <iostream>
#include <string>
using namespace std;
class Parent 
{
public:
    Parent()
    {
        cout << "Parent()" << endl;
    }
    Parent(string s)
    {
        cout << "Parent(string s) : " << s << endl;
    }
};
class Child : public Parent
{
public:
    Child()           默认方式    //隐式调用父类无参数构造函数,父类没有会报错
    {
        cout << "Child()" << endl;
    }
    Child(string s) : Parent(s)       //显示调用父类构造函数
    {
        cout << "Child(string s) : " << s << endl;
    }
};
int main()
{       
    Child c;    //parent()  child()
    Child cc("cc");      //parent(string s) : cc       child(string s) : cc
    return 0;

}

构造规则:子类对象在创建时会首先调用父类的构造函数,先执行父类构造函数再执行子类的构造函数,父类构造函数可以被隐式调用(无参构造函数或者使用有默认值的构造函数)或者显示调用。

对象创建时构造函数的调用顺序:1、调用父类的构造函数。2、调用成员变量的构造函数。3、调用类自身的构造函数。

口诀心法:先父母,后客人,再自己。

#include <iostream>
#include <string>
using namespace std;
class Object
{
    string ms;
public:
    Object(string s)
    {
        cout << "Object(string s) : " << s << endl;
        ms = s;
    }
    ~Object()
    {
        cout << "~Object() : " << ms << endl;
    }
};
class Parent : public Object
{
    string ms;
public:
    Parent() : Object("Default")      //显示调用
    {
        cout << "Parent()" << endl;
        ms = "Default";
    }
    Parent(string s) : Object(s)
    {
        cout << "Parent(string s) : " << s << endl;
        ms = s;
    }
    ~Parent()
    {
        cout << "~Parent() : " << ms << endl;
    }
};
class Child : public Parent
{
    Object mO1;           //客人
    Object mO2;
    string ms;
public:
    Child() : mO1("Default 1"), mO2("Default 2")
    {
        cout << "Child()" << endl;
        ms = "Default";
    }
    Child(string s) : Parent(s), mO1(s + " 1"), mO2(s + " 2")     //先父母,后客人
    {
        cout << "Child(string s) : " << s << endl;
        ms = s;
    }
    ~Child()
    {
        cout << "~Child() " << ms << endl;
    }
};
int main()
{       
    Child cc("cc");    //  先父母: Object(string s) :cc  Parent(string s) : cc  后客人: Object(string s) :cc1
                               //  Object(string s) :cc2    再自己:Child(string s) : cc
    cout << endl;
    
    return 0;

}

析构函数的调用顺序与构造函数相反:

1、执行自身的析构函数。2、执行成员变量的析构函数。3、执行父类的析构函数。

子类对象在创建时需要调用父类构造函数进行初始化。先执行父类构造函数然后执行成员的构造函数,父类构造函数显示调用需要在初始化列表中进行,子类对象在销毁时需要调用父类析构函数进行清理,析构顺序与构造顺序对称相反。

猜你喜欢

转载自blog.csdn.net/ws857707645/article/details/80251968
今日推荐