先构造的后析构
复合(一个类包含另一个类) 构造由内而外 析构由外而内
委托(一个类包含另一个类的指针)
派生类想要通过初始化列表 初始继承的成员变量时,不可以直接调用自己的构造函数,需要显示的调用基类的构造函数
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A(int a, int b, int c) :a(a), b(b), c(c) {}
virtual void print() = 0;
virtual ~A() {}
int a;
int b;
int c;
};
class B:public A
{
public:
B(int a,int b,int c):A(a,b,c){}
virtual void print() override {
cout << a << " " << b << " " << c << endl;
}
virtual ~B() {}
};
int main()
{
A* a = new B(1, 3, 4);
a->print();
return 0;
}
在继承和派生关系中,基类的构造函数会先被调用
#include <iostream>
class A
{
public:
A(int a)
: a_(a)
{
std::cout << "A constructor " << a_ << std::endl;
}
~A()
{
std::cout << "~A destructor" << std::endl;
}
int a_;
};
class B : public A // inherit
{
public:
B(int b)
: A(111), b_(b)
{
std::cout << "B constructor " << b_ << std::endl;
}
~B()
{
std::cout << "~B destructor" << std::endl;
}
int b_;
};
class C
{
public:
C(int c)
: c_(c), b(222)
{
std::cout << "C constructor " << c_ << std::endl;
}
~C()
{
std::cout << "~C desturtor" << std::endl;
}
int c_;
B b;
};
int main()
{
C c(333);
return 0;
}