派生类的构造与析构函数(C++)

2023-12-29 22:30:29

3.3 派生类的构造与析构函数

3.3.1 构造

  • 如果子类构造函数没有显式指明基类部分(基类子对象)的初始化方式,那么编译器将会自动调用基类的无参构造函数来初始化基类子对象。

  • 如果希望以有参的方式来初始化基类部分,那么必须使用初始化列表来显式指明

  • 子对象构造顺序

    • 分配内存
    • 构造基类子对象(按继承表顺序)
    • 构造成员子对象(按声明顺序)
    • 执行子类构造函数代码
    #include <iostream>
    using namespace std;
    
    class Member{
    private:
    	int m_m;
    public:
    	Member(){
    		cout << "Member()" << endl;
    	}
    	Member(int m) {
    		cout << "Member(int)" << endl;
    		m_m = m;
    	}
    };
    
    class Base {
    private:
    	int m_i;
    public:
    	Base(){
    		cout << "Base()" << endl;
    	}
    	Base(int i){
    		cout << "Base(int)" << endl;
    		m_i = i;
    	}
    };
    
    class Derived:public Base{
    private:
    	int m_d;
    	Member m_me;
    public:
    	Derived(){
    		cout << "Derived()" << endl;//不指定作用域 默认调用无惨构造函数
    	}
    	Derived(int d):Base(d), m_me(d){ //指定作用域 就调用有参构造函
    		cout << "Derived(int)" << endl;
    		m_d = d;
    	}
    };
    int main (void) {
    	Derived d1;
    	Derived d2(100);
    	return 0;
    }
    

3.3.2 析构

  • 子类的析构函数,无论自己定义的,还是编译器缺省提供,都会自动调用基类的析构函数,完成基类子对象的销毁

  • 子类对象销毁过程

    • 执行子类析构函数代码
    • 析构成员子对象(按声明逆序)
    • 析构基类子对象(按继承表逆序)
    • 释放内存
    #include <iostream>
    using namespace std;
    
    class Member{
    private:
    	int m_m;
    public:
    	Member(){
    		cout << "Member()" << endl;
    	}
    	Member(int m) {
    		cout << "Member(int)" << endl;
    		m_m = m;
    	}
    	~Member(){
    		cout << "~Member()" << endl;
    	}
    };
    
    class Base {
    private:
    	int m_i;
    public:
    	Base(){
    		cout << "Base()" << endl;
    	}
    	Base(int i){
    		cout << "Base(int)" << endl;
    		m_i = i;
    	}
    	~Base(){
    		cout << "~Base()" << endl;
    	}
    };
    
    class Derived:public Base{
    private:
    	int m_d;
    	Member m_me;
    public:
    	Derived(){
    		cout << "Derived()" << endl;//不指定作用域 默认调用无惨构造函数
    	}
    	Derived(int d):Base(d), m_me(d){ //指定作用域 就调用有参构造函
    		cout << "Derived(int)" << endl;
    		m_d = d;
    	}
    	~Derived(){
    		cout << "~Derived()" << endl;
    	}
    };
    int main (void) {
    	Derived d1;
    	return 0;
    }
    
    //输出结果:
    myubuntu@ubuntu:~/lv19/cplusplus/dy03$ ./a.out 
    Base()
    Member()
    Derived()
    ~Derived()
    ~Member()
    ~Base()
    

文章来源:https://blog.csdn.net/qq_36091214/article/details/135298727
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。