实例:
#include <iostream>
using namespace std;
class parent{
public:
parent(int a, int b, int d)
{
this->a = a;
this->b = b;
this->d = d;
cout << "基类构造" << endl;
}
~parent()
{
cout << "基类析构" << endl;
}
public:
int a;
private:
int b;
protected:
int d;
};
class child3 : public parent
{
public:
child3(int c, int a, int b, int d) : parent(a, b, d)
{
this->c = c;
cout << "派生类构造函数" << endl;
}
~child3()
{
cout << "派生类析构函数" << endl;
}
public:
private:
int c;
protected:
};
int main()
{
{
child3 oop(1, 2, 3, 3);
}
system("pause");
return 0;
}
在上述代码中,程序在执行时会先进入到基类的构造函数执行parent(int a,int b,int c)构造函数,当构造函数执行结束后打印基类构造函数,然后继续执行child3的构造函数child3(int c,int a,int b,int d),当该构造函数执行结束后打印派生类构造函数,然后进入到派生类析构函数执行,执行完成最后执行基类析构函数,最后打印基类析构函数;
混搭情况下构造和析构函数的调用规则:
构造:先调用父类构造函数,在调用构造成员,最后调用自己的构造函数;
析构:先析构自己,在析构成员变量,最后析构父类
#include <iostream>
using namespace std;
class Grad{
public:
Grad(int _a, int _b)
{
this->_a = _a;
this->_b = _b;
cout << "Grad 构造函数" << endl;
}
~Grad()
{
cout << "Grad析构函数" << endl;
}
private:
int _a;
int _b;
};
class parent
{
public:
parent(int a, int b, int d)
{
this->a = a;
this->b = b;
this->d = d;
cout << "基类构造" << endl;
}
~parent()
{
cout << "基类析构" << endl;
}
public:
int a;
private:
int b;
protected:
int d;
};
class child3 : public parent
{
public:
child3(int c, int a, int b, int d) : parent(a, b, d), oop1(5, 6), oop2(7,8)
{
this->c = c;
cout << "派生类构造函数" << endl;
}
~child3()
{
cout << "派生类析构函数" << endl;
}
public:
Grad oop1;
Grad oop2;
private:
int c;
protected:
};
int main()
{
{
child3 oop(1, 2, 3, 3);
}
system("pause");
return 0;
}