關於類的指針對象調用構造函數


一個類的指針對象,如果分配空間的話,就會調用構造函數,在析構時要手動調用delete

如果沒有分配就,不會調用。

還有就是,對象析構的順序是先析構下面的在析構上面的

A a;
B b;
就會先析構b,在析構a

 

看看下面的例子

//
// Created by LK on 2020/3/31.
//

#include <iostream>
using namespace std;
class a
{
public:
    a()
    {
        cout << "this is a 構造函數"<<endl;
    }
    virtual void f1()
    {
        cout << "this is a f1" << endl;
    }
    virtual void f2()
    {
        cout << "this is a f2" << endl;
    }
    ~a()
    {
        cout << "this is a 析構函數" << endl;
    }
};

class b : public  a
{
public:

    b()
    {
        cout << "this is b 構造函數"<< endl;
    }
    virtual void f1()
    {
        cout <<"this is b f1" << endl;
    }
    ~b()
    {
          cout << "this is b 析構函數" << endl;
    }

};
// 對象釋放的順序是 從下往上的,就是先進行bb的析構,在進行aa的析構
// 因為 指針p沒有分配空間,所以不調用構造函數,和析構函數
// 如果是 a *p = new a; 就要調用構造函數了,要調用delete 才能調用析構函數


int main()
{
    a aa, *p;
    b bb;
    p = &aa;
    p->f1(); p->f2();

    p = &bb;
    p->f1(); p->f2();

/*
    {
        a *p2 = new a;
        delete p2;

//        this is a 構造函數
//        this is a 析構函數
    }
    */

    return 0;
}

執行結果

this is a 構造函數
this is a 構造函數
this is b 構造函數
this is a f1
this is a f2
this is b f1
this is a f2
this is b 析構函數
this is a 析構函數
this is a 析構函數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM