关于类的指针对象调用构造函数

一个类的指针对象,如果分配空间的话,就会调用构造函数,在析构时要手动调用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 析构函数
原文地址:https://www.cnblogs.com/xiaokang01/p/12615985.html